1 /**
2 * Simple build automation tool.
3 *
4 * Authors:
5 * Bob Jamison
6 * Jasper van de Gronde
7 *
8 * Copyright (C) 2006-2008 Bob Jamison
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23 */
25 /**
26 * To use this file, compile with:
27 * <pre>
28 * g++ -O3 buildtool.cpp -o btool.exe
29 * (or whatever your compiler might be)
30 * Then
31 * btool
32 * or
33 * btool {target}
34 *
35 * Note: if you are using MinGW, and a not very recent version of it,
36 * gettimeofday() might be missing. If so, just build this file with
37 * this command:
38 * g++ -O3 -DNEED_GETTIMEOFDAY buildtool.cpp -o btool.exe
39 *
40 */
42 #define BUILDTOOL_VERSION "BuildTool v0.9.9"
44 #include <stdio.h>
45 #include <fcntl.h>
46 #include <unistd.h>
47 #include <stdarg.h>
48 #include <sys/stat.h>
49 #include <time.h>
50 #include <sys/time.h>
51 #include <utime.h>
52 #include <dirent.h>
54 #include <string>
55 #include <map>
56 #include <set>
57 #include <vector>
58 #include <algorithm>
61 #ifdef __WIN32__
62 #include <windows.h>
63 #endif
66 #include <errno.h>
69 //########################################################################
70 //# Definition of gettimeofday() for those who don't have it
71 //########################################################################
72 #ifdef NEED_GETTIMEOFDAY
73 #include <sys/timeb.h>
75 struct timezone {
76 int tz_minuteswest; /* minutes west of Greenwich */
77 int tz_dsttime; /* type of dst correction */
78 };
80 static int gettimeofday (struct timeval *tv, struct timezone *tz)
81 {
82 struct _timeb tb;
84 if (!tv)
85 return (-1);
87 _ftime (&tb);
88 tv->tv_sec = tb.time;
89 tv->tv_usec = tb.millitm * 1000 + 500;
90 if (tz)
91 {
92 tz->tz_minuteswest = -60 * _timezone;
93 tz->tz_dsttime = _daylight;
94 }
95 return 0;
96 }
98 #endif
106 namespace buildtool
107 {
112 //########################################################################
113 //########################################################################
114 //## R E G E X P
115 //########################################################################
116 //########################################################################
118 /**
119 * This is the T-Rex regular expression library, which we
120 * gratefully acknowledge. It's clean code and small size allow
121 * us to embed it in BuildTool without adding a dependency
122 *
123 */
125 //begin trex.h
127 #ifndef _TREX_H_
128 #define _TREX_H_
129 /***************************************************************
130 T-Rex a tiny regular expression library
132 Copyright (C) 2003-2006 Alberto Demichelis
134 This software is provided 'as-is', without any express
135 or implied warranty. In no event will the authors be held
136 liable for any damages arising from the use of this software.
138 Permission is granted to anyone to use this software for
139 any purpose, including commercial applications, and to alter
140 it and redistribute it freely, subject to the following restrictions:
142 1. The origin of this software must not be misrepresented;
143 you must not claim that you wrote the original software.
144 If you use this software in a product, an acknowledgment
145 in the product documentation would be appreciated but
146 is not required.
148 2. Altered source versions must be plainly marked as such,
149 and must not be misrepresented as being the original software.
151 3. This notice may not be removed or altered from any
152 source distribution.
154 ****************************************************************/
156 #ifdef _UNICODE
157 #define TRexChar unsigned short
158 #define MAX_CHAR 0xFFFF
159 #define _TREXC(c) L##c
160 #define trex_strlen wcslen
161 #define trex_printf wprintf
162 #else
163 #define TRexChar char
164 #define MAX_CHAR 0xFF
165 #define _TREXC(c) (c)
166 #define trex_strlen strlen
167 #define trex_printf printf
168 #endif
170 #ifndef TREX_API
171 #define TREX_API extern
172 #endif
174 #define TRex_True 1
175 #define TRex_False 0
177 typedef unsigned int TRexBool;
178 typedef struct TRex TRex;
180 typedef struct {
181 const TRexChar *begin;
182 int len;
183 } TRexMatch;
185 TREX_API TRex *trex_compile(const TRexChar *pattern,const TRexChar **error);
186 TREX_API void trex_free(TRex *exp);
187 TREX_API TRexBool trex_match(TRex* exp,const TRexChar* text);
188 TREX_API TRexBool trex_search(TRex* exp,const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end);
189 TREX_API TRexBool trex_searchrange(TRex* exp,const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end);
190 TREX_API int trex_getsubexpcount(TRex* exp);
191 TREX_API TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch *subexp);
193 #endif
195 //end trex.h
197 //start trex.c
200 #include <stdio.h>
201 #include <string>
203 /* see copyright notice in trex.h */
204 #include <string.h>
205 #include <stdlib.h>
206 #include <ctype.h>
207 #include <setjmp.h>
208 //#include "trex.h"
210 #ifdef _UNICODE
211 #define scisprint iswprint
212 #define scstrlen wcslen
213 #define scprintf wprintf
214 #define _SC(x) L(x)
215 #else
216 #define scisprint isprint
217 #define scstrlen strlen
218 #define scprintf printf
219 #define _SC(x) (x)
220 #endif
222 #ifdef _DEBUG
223 #include <stdio.h>
225 static const TRexChar *g_nnames[] =
226 {
227 _SC("NONE"),_SC("OP_GREEDY"), _SC("OP_OR"),
228 _SC("OP_EXPR"),_SC("OP_NOCAPEXPR"),_SC("OP_DOT"), _SC("OP_CLASS"),
229 _SC("OP_CCLASS"),_SC("OP_NCLASS"),_SC("OP_RANGE"),_SC("OP_CHAR"),
230 _SC("OP_EOL"),_SC("OP_BOL"),_SC("OP_WB")
231 };
233 #endif
234 #define OP_GREEDY (MAX_CHAR+1) // * + ? {n}
235 #define OP_OR (MAX_CHAR+2)
236 #define OP_EXPR (MAX_CHAR+3) //parentesis ()
237 #define OP_NOCAPEXPR (MAX_CHAR+4) //parentesis (?:)
238 #define OP_DOT (MAX_CHAR+5)
239 #define OP_CLASS (MAX_CHAR+6)
240 #define OP_CCLASS (MAX_CHAR+7)
241 #define OP_NCLASS (MAX_CHAR+8) //negates class the [^
242 #define OP_RANGE (MAX_CHAR+9)
243 #define OP_CHAR (MAX_CHAR+10)
244 #define OP_EOL (MAX_CHAR+11)
245 #define OP_BOL (MAX_CHAR+12)
246 #define OP_WB (MAX_CHAR+13)
248 #define TREX_SYMBOL_ANY_CHAR ('.')
249 #define TREX_SYMBOL_GREEDY_ONE_OR_MORE ('+')
250 #define TREX_SYMBOL_GREEDY_ZERO_OR_MORE ('*')
251 #define TREX_SYMBOL_GREEDY_ZERO_OR_ONE ('?')
252 #define TREX_SYMBOL_BRANCH ('|')
253 #define TREX_SYMBOL_END_OF_STRING ('$')
254 #define TREX_SYMBOL_BEGINNING_OF_STRING ('^')
255 #define TREX_SYMBOL_ESCAPE_CHAR ('\\')
258 typedef int TRexNodeType;
260 typedef struct tagTRexNode{
261 TRexNodeType type;
262 int left;
263 int right;
264 int next;
265 }TRexNode;
267 struct TRex{
268 const TRexChar *_eol;
269 const TRexChar *_bol;
270 const TRexChar *_p;
271 int _first;
272 int _op;
273 TRexNode *_nodes;
274 int _nallocated;
275 int _nsize;
276 int _nsubexpr;
277 TRexMatch *_matches;
278 int _currsubexp;
279 void *_jmpbuf;
280 const TRexChar **_error;
281 };
283 static int trex_list(TRex *exp);
285 static int trex_newnode(TRex *exp, TRexNodeType type)
286 {
287 TRexNode n;
288 int newid;
289 n.type = type;
290 n.next = n.right = n.left = -1;
291 if(type == OP_EXPR)
292 n.right = exp->_nsubexpr++;
293 if(exp->_nallocated < (exp->_nsize + 1)) {
294 //int oldsize = exp->_nallocated;
295 exp->_nallocated *= 2;
296 exp->_nodes = (TRexNode *)realloc(exp->_nodes, exp->_nallocated * sizeof(TRexNode));
297 }
298 exp->_nodes[exp->_nsize++] = n;
299 newid = exp->_nsize - 1;
300 return (int)newid;
301 }
303 static void trex_error(TRex *exp,const TRexChar *error)
304 {
305 if(exp->_error) *exp->_error = error;
306 longjmp(*((jmp_buf*)exp->_jmpbuf),-1);
307 }
309 static void trex_expect(TRex *exp, int n){
310 if((*exp->_p) != n)
311 trex_error(exp, _SC("expected paren"));
312 exp->_p++;
313 }
315 static TRexChar trex_escapechar(TRex *exp)
316 {
317 if(*exp->_p == TREX_SYMBOL_ESCAPE_CHAR){
318 exp->_p++;
319 switch(*exp->_p) {
320 case 'v': exp->_p++; return '\v';
321 case 'n': exp->_p++; return '\n';
322 case 't': exp->_p++; return '\t';
323 case 'r': exp->_p++; return '\r';
324 case 'f': exp->_p++; return '\f';
325 default: return (*exp->_p++);
326 }
327 } else if(!scisprint(*exp->_p)) trex_error(exp,_SC("letter expected"));
328 return (*exp->_p++);
329 }
331 static int trex_charclass(TRex *exp,int classid)
332 {
333 int n = trex_newnode(exp,OP_CCLASS);
334 exp->_nodes[n].left = classid;
335 return n;
336 }
338 static int trex_charnode(TRex *exp,TRexBool isclass)
339 {
340 TRexChar t;
341 if(*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) {
342 exp->_p++;
343 switch(*exp->_p) {
344 case 'n': exp->_p++; return trex_newnode(exp,'\n');
345 case 't': exp->_p++; return trex_newnode(exp,'\t');
346 case 'r': exp->_p++; return trex_newnode(exp,'\r');
347 case 'f': exp->_p++; return trex_newnode(exp,'\f');
348 case 'v': exp->_p++; return trex_newnode(exp,'\v');
349 case 'a': case 'A': case 'w': case 'W': case 's': case 'S':
350 case 'd': case 'D': case 'x': case 'X': case 'c': case 'C':
351 case 'p': case 'P': case 'l': case 'u':
352 {
353 t = *exp->_p; exp->_p++;
354 return trex_charclass(exp,t);
355 }
356 case 'b':
357 case 'B':
358 if(!isclass) {
359 int node = trex_newnode(exp,OP_WB);
360 exp->_nodes[node].left = *exp->_p;
361 exp->_p++;
362 return node;
363 } //else default
364 default:
365 t = *exp->_p; exp->_p++;
366 return trex_newnode(exp,t);
367 }
368 }
369 else if(!scisprint(*exp->_p)) {
371 trex_error(exp,_SC("letter expected"));
372 }
373 t = *exp->_p; exp->_p++;
374 return trex_newnode(exp,t);
375 }
376 static int trex_class(TRex *exp)
377 {
378 int ret = -1;
379 int first = -1,chain;
380 if(*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING){
381 ret = trex_newnode(exp,OP_NCLASS);
382 exp->_p++;
383 }else ret = trex_newnode(exp,OP_CLASS);
385 if(*exp->_p == ']') trex_error(exp,_SC("empty class"));
386 chain = ret;
387 while(*exp->_p != ']' && exp->_p != exp->_eol) {
388 if(*exp->_p == '-' && first != -1){
389 int r,t;
390 if(*exp->_p++ == ']') trex_error(exp,_SC("unfinished range"));
391 r = trex_newnode(exp,OP_RANGE);
392 if(first>*exp->_p) trex_error(exp,_SC("invalid range"));
393 if(exp->_nodes[first].type == OP_CCLASS) trex_error(exp,_SC("cannot use character classes in ranges"));
394 exp->_nodes[r].left = exp->_nodes[first].type;
395 t = trex_escapechar(exp);
396 exp->_nodes[r].right = t;
397 exp->_nodes[chain].next = r;
398 chain = r;
399 first = -1;
400 }
401 else{
402 if(first!=-1){
403 int c = first;
404 exp->_nodes[chain].next = c;
405 chain = c;
406 first = trex_charnode(exp,TRex_True);
407 }
408 else{
409 first = trex_charnode(exp,TRex_True);
410 }
411 }
412 }
413 if(first!=-1){
414 int c = first;
415 exp->_nodes[chain].next = c;
416 chain = c;
417 first = -1;
418 }
419 /* hack? */
420 exp->_nodes[ret].left = exp->_nodes[ret].next;
421 exp->_nodes[ret].next = -1;
422 return ret;
423 }
425 static int trex_parsenumber(TRex *exp)
426 {
427 int ret = *exp->_p-'0';
428 int positions = 10;
429 exp->_p++;
430 while(isdigit(*exp->_p)) {
431 ret = ret*10+(*exp->_p++-'0');
432 if(positions==1000000000) trex_error(exp,_SC("overflow in numeric constant"));
433 positions *= 10;
434 };
435 return ret;
436 }
438 static int trex_element(TRex *exp)
439 {
440 int ret = -1;
441 switch(*exp->_p)
442 {
443 case '(': {
444 int expr,newn;
445 exp->_p++;
448 if(*exp->_p =='?') {
449 exp->_p++;
450 trex_expect(exp,':');
451 expr = trex_newnode(exp,OP_NOCAPEXPR);
452 }
453 else
454 expr = trex_newnode(exp,OP_EXPR);
455 newn = trex_list(exp);
456 exp->_nodes[expr].left = newn;
457 ret = expr;
458 trex_expect(exp,')');
459 }
460 break;
461 case '[':
462 exp->_p++;
463 ret = trex_class(exp);
464 trex_expect(exp,']');
465 break;
466 case TREX_SYMBOL_END_OF_STRING: exp->_p++; ret = trex_newnode(exp,OP_EOL);break;
467 case TREX_SYMBOL_ANY_CHAR: exp->_p++; ret = trex_newnode(exp,OP_DOT);break;
468 default:
469 ret = trex_charnode(exp,TRex_False);
470 break;
471 }
473 {
474 int op;
475 TRexBool isgreedy = TRex_False;
476 unsigned short p0 = 0, p1 = 0;
477 switch(*exp->_p){
478 case TREX_SYMBOL_GREEDY_ZERO_OR_MORE: p0 = 0; p1 = 0xFFFF; exp->_p++; isgreedy = TRex_True; break;
479 case TREX_SYMBOL_GREEDY_ONE_OR_MORE: p0 = 1; p1 = 0xFFFF; exp->_p++; isgreedy = TRex_True; break;
480 case TREX_SYMBOL_GREEDY_ZERO_OR_ONE: p0 = 0; p1 = 1; exp->_p++; isgreedy = TRex_True; break;
481 case '{':
482 exp->_p++;
483 if(!isdigit(*exp->_p)) trex_error(exp,_SC("number expected"));
484 p0 = (unsigned short)trex_parsenumber(exp);
485 /*******************************/
486 switch(*exp->_p) {
487 case '}':
488 p1 = p0; exp->_p++;
489 break;
490 case ',':
491 exp->_p++;
492 p1 = 0xFFFF;
493 if(isdigit(*exp->_p)){
494 p1 = (unsigned short)trex_parsenumber(exp);
495 }
496 trex_expect(exp,'}');
497 break;
498 default:
499 trex_error(exp,_SC(", or } expected"));
500 }
501 /*******************************/
502 isgreedy = TRex_True;
503 break;
505 }
506 if(isgreedy) {
507 int nnode = trex_newnode(exp,OP_GREEDY);
508 op = OP_GREEDY;
509 exp->_nodes[nnode].left = ret;
510 exp->_nodes[nnode].right = ((p0)<<16)|p1;
511 ret = nnode;
512 }
513 }
514 if((*exp->_p != TREX_SYMBOL_BRANCH) && (*exp->_p != ')') && (*exp->_p != TREX_SYMBOL_GREEDY_ZERO_OR_MORE) && (*exp->_p != TREX_SYMBOL_GREEDY_ONE_OR_MORE) && (*exp->_p != '\0')) {
515 int nnode = trex_element(exp);
516 exp->_nodes[ret].next = nnode;
517 }
519 return ret;
520 }
522 static int trex_list(TRex *exp)
523 {
524 int ret=-1,e;
525 if(*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) {
526 exp->_p++;
527 ret = trex_newnode(exp,OP_BOL);
528 }
529 e = trex_element(exp);
530 if(ret != -1) {
531 exp->_nodes[ret].next = e;
532 }
533 else ret = e;
535 if(*exp->_p == TREX_SYMBOL_BRANCH) {
536 int temp,tright;
537 exp->_p++;
538 temp = trex_newnode(exp,OP_OR);
539 exp->_nodes[temp].left = ret;
540 tright = trex_list(exp);
541 exp->_nodes[temp].right = tright;
542 ret = temp;
543 }
544 return ret;
545 }
547 static TRexBool trex_matchcclass(int cclass,TRexChar c)
548 {
549 switch(cclass) {
550 case 'a': return isalpha(c)?TRex_True:TRex_False;
551 case 'A': return !isalpha(c)?TRex_True:TRex_False;
552 case 'w': return (isalnum(c) || c == '_')?TRex_True:TRex_False;
553 case 'W': return (!isalnum(c) && c != '_')?TRex_True:TRex_False;
554 case 's': return isspace(c)?TRex_True:TRex_False;
555 case 'S': return !isspace(c)?TRex_True:TRex_False;
556 case 'd': return isdigit(c)?TRex_True:TRex_False;
557 case 'D': return !isdigit(c)?TRex_True:TRex_False;
558 case 'x': return isxdigit(c)?TRex_True:TRex_False;
559 case 'X': return !isxdigit(c)?TRex_True:TRex_False;
560 case 'c': return iscntrl(c)?TRex_True:TRex_False;
561 case 'C': return !iscntrl(c)?TRex_True:TRex_False;
562 case 'p': return ispunct(c)?TRex_True:TRex_False;
563 case 'P': return !ispunct(c)?TRex_True:TRex_False;
564 case 'l': return islower(c)?TRex_True:TRex_False;
565 case 'u': return isupper(c)?TRex_True:TRex_False;
566 }
567 return TRex_False; /*cannot happen*/
568 }
570 static TRexBool trex_matchclass(TRex* exp,TRexNode *node,TRexChar c)
571 {
572 do {
573 switch(node->type) {
574 case OP_RANGE:
575 if(c >= node->left && c <= node->right) return TRex_True;
576 break;
577 case OP_CCLASS:
578 if(trex_matchcclass(node->left,c)) return TRex_True;
579 break;
580 default:
581 if(c == node->type)return TRex_True;
582 }
583 } while((node->next != -1) && (node = &exp->_nodes[node->next]));
584 return TRex_False;
585 }
587 static const TRexChar *trex_matchnode(TRex* exp,TRexNode *node,const TRexChar *str,TRexNode *next)
588 {
590 TRexNodeType type = node->type;
591 switch(type) {
592 case OP_GREEDY: {
593 //TRexNode *greedystop = (node->next != -1) ? &exp->_nodes[node->next] : NULL;
594 TRexNode *greedystop = NULL;
595 int p0 = (node->right >> 16)&0x0000FFFF, p1 = node->right&0x0000FFFF, nmaches = 0;
596 const TRexChar *s=str, *good = str;
598 if(node->next != -1) {
599 greedystop = &exp->_nodes[node->next];
600 }
601 else {
602 greedystop = next;
603 }
605 while((nmaches == 0xFFFF || nmaches < p1)) {
607 const TRexChar *stop;
608 if(!(s = trex_matchnode(exp,&exp->_nodes[node->left],s,greedystop)))
609 break;
610 nmaches++;
611 good=s;
612 if(greedystop) {
613 //checks that 0 matches satisfy the expression(if so skips)
614 //if not would always stop(for instance if is a '?')
615 if(greedystop->type != OP_GREEDY ||
616 (greedystop->type == OP_GREEDY && ((greedystop->right >> 16)&0x0000FFFF) != 0))
617 {
618 TRexNode *gnext = NULL;
619 if(greedystop->next != -1) {
620 gnext = &exp->_nodes[greedystop->next];
621 }else if(next && next->next != -1){
622 gnext = &exp->_nodes[next->next];
623 }
624 stop = trex_matchnode(exp,greedystop,s,gnext);
625 if(stop) {
626 //if satisfied stop it
627 if(p0 == p1 && p0 == nmaches) break;
628 else if(nmaches >= p0 && p1 == 0xFFFF) break;
629 else if(nmaches >= p0 && nmaches <= p1) break;
630 }
631 }
632 }
634 if(s >= exp->_eol)
635 break;
636 }
637 if(p0 == p1 && p0 == nmaches) return good;
638 else if(nmaches >= p0 && p1 == 0xFFFF) return good;
639 else if(nmaches >= p0 && nmaches <= p1) return good;
640 return NULL;
641 }
642 case OP_OR: {
643 const TRexChar *asd = str;
644 TRexNode *temp=&exp->_nodes[node->left];
645 while( (asd = trex_matchnode(exp,temp,asd,NULL)) ) {
646 if(temp->next != -1)
647 temp = &exp->_nodes[temp->next];
648 else
649 return asd;
650 }
651 asd = str;
652 temp = &exp->_nodes[node->right];
653 while( (asd = trex_matchnode(exp,temp,asd,NULL)) ) {
654 if(temp->next != -1)
655 temp = &exp->_nodes[temp->next];
656 else
657 return asd;
658 }
659 return NULL;
660 break;
661 }
662 case OP_EXPR:
663 case OP_NOCAPEXPR:{
664 TRexNode *n = &exp->_nodes[node->left];
665 const TRexChar *cur = str;
666 int capture = -1;
667 if(node->type != OP_NOCAPEXPR && node->right == exp->_currsubexp) {
668 capture = exp->_currsubexp;
669 exp->_matches[capture].begin = cur;
670 exp->_currsubexp++;
671 }
673 do {
674 TRexNode *subnext = NULL;
675 if(n->next != -1) {
676 subnext = &exp->_nodes[n->next];
677 }else {
678 subnext = next;
679 }
680 if(!(cur = trex_matchnode(exp,n,cur,subnext))) {
681 if(capture != -1){
682 exp->_matches[capture].begin = 0;
683 exp->_matches[capture].len = 0;
684 }
685 return NULL;
686 }
687 } while((n->next != -1) && (n = &exp->_nodes[n->next]));
689 if(capture != -1)
690 exp->_matches[capture].len = cur - exp->_matches[capture].begin;
691 return cur;
692 }
693 case OP_WB:
694 if((str == exp->_bol && !isspace(*str))
695 || (str == exp->_eol && !isspace(*(str-1)))
696 || (!isspace(*str) && isspace(*(str+1)))
697 || (isspace(*str) && !isspace(*(str+1))) ) {
698 return (node->left == 'b')?str:NULL;
699 }
700 return (node->left == 'b')?NULL:str;
701 case OP_BOL:
702 if(str == exp->_bol) return str;
703 return NULL;
704 case OP_EOL:
705 if(str == exp->_eol) return str;
706 return NULL;
707 case OP_DOT:{
708 *str++;
709 }
710 return str;
711 case OP_NCLASS:
712 case OP_CLASS:
713 if(trex_matchclass(exp,&exp->_nodes[node->left],*str)?(type == OP_CLASS?TRex_True:TRex_False):(type == OP_NCLASS?TRex_True:TRex_False)) {
714 *str++;
715 return str;
716 }
717 return NULL;
718 case OP_CCLASS:
719 if(trex_matchcclass(node->left,*str)) {
720 *str++;
721 return str;
722 }
723 return NULL;
724 default: /* char */
725 if(*str != node->type) return NULL;
726 *str++;
727 return str;
728 }
729 return NULL;
730 }
732 /* public api */
733 TRex *trex_compile(const TRexChar *pattern,const TRexChar **error)
734 {
735 TRex *exp = (TRex *)malloc(sizeof(TRex));
736 exp->_eol = exp->_bol = NULL;
737 exp->_p = pattern;
738 exp->_nallocated = (int)scstrlen(pattern) * sizeof(TRexChar);
739 exp->_nodes = (TRexNode *)malloc(exp->_nallocated * sizeof(TRexNode));
740 exp->_nsize = 0;
741 exp->_matches = 0;
742 exp->_nsubexpr = 0;
743 exp->_first = trex_newnode(exp,OP_EXPR);
744 exp->_error = error;
745 exp->_jmpbuf = malloc(sizeof(jmp_buf));
746 if(setjmp(*((jmp_buf*)exp->_jmpbuf)) == 0) {
747 int res = trex_list(exp);
748 exp->_nodes[exp->_first].left = res;
749 if(*exp->_p!='\0')
750 trex_error(exp,_SC("unexpected character"));
751 #ifdef _DEBUG
752 {
753 int nsize,i;
754 TRexNode *t;
755 nsize = exp->_nsize;
756 t = &exp->_nodes[0];
757 scprintf(_SC("\n"));
758 for(i = 0;i < nsize; i++) {
759 if(exp->_nodes[i].type>MAX_CHAR)
760 scprintf(_SC("[%02d] %10s "),i,g_nnames[exp->_nodes[i].type-MAX_CHAR]);
761 else
762 scprintf(_SC("[%02d] %10c "),i,exp->_nodes[i].type);
763 scprintf(_SC("left %02d right %02d next %02d\n"),exp->_nodes[i].left,exp->_nodes[i].right,exp->_nodes[i].next);
764 }
765 scprintf(_SC("\n"));
766 }
767 #endif
768 exp->_matches = (TRexMatch *) malloc(exp->_nsubexpr * sizeof(TRexMatch));
769 memset(exp->_matches,0,exp->_nsubexpr * sizeof(TRexMatch));
770 }
771 else{
772 trex_free(exp);
773 return NULL;
774 }
775 return exp;
776 }
778 void trex_free(TRex *exp)
779 {
780 if(exp) {
781 if(exp->_nodes) free(exp->_nodes);
782 if(exp->_jmpbuf) free(exp->_jmpbuf);
783 if(exp->_matches) free(exp->_matches);
784 free(exp);
785 }
786 }
788 TRexBool trex_match(TRex* exp,const TRexChar* text)
789 {
790 const TRexChar* res = NULL;
791 exp->_bol = text;
792 exp->_eol = text + scstrlen(text);
793 exp->_currsubexp = 0;
794 res = trex_matchnode(exp,exp->_nodes,text,NULL);
795 if(res == NULL || res != exp->_eol)
796 return TRex_False;
797 return TRex_True;
798 }
800 TRexBool trex_searchrange(TRex* exp,const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end)
801 {
802 const TRexChar *cur = NULL;
803 int node = exp->_first;
804 if(text_begin >= text_end) return TRex_False;
805 exp->_bol = text_begin;
806 exp->_eol = text_end;
807 do {
808 cur = text_begin;
809 while(node != -1) {
810 exp->_currsubexp = 0;
811 cur = trex_matchnode(exp,&exp->_nodes[node],cur,NULL);
812 if(!cur)
813 break;
814 node = exp->_nodes[node].next;
815 }
816 *text_begin++;
817 } while(cur == NULL && text_begin != text_end);
819 if(cur == NULL)
820 return TRex_False;
822 --text_begin;
824 if(out_begin) *out_begin = text_begin;
825 if(out_end) *out_end = cur;
826 return TRex_True;
827 }
829 TRexBool trex_search(TRex* exp,const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end)
830 {
831 return trex_searchrange(exp,text,text + scstrlen(text),out_begin,out_end);
832 }
834 int trex_getsubexpcount(TRex* exp)
835 {
836 return exp->_nsubexpr;
837 }
839 TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch *subexp)
840 {
841 if( n<0 || n >= exp->_nsubexpr) return TRex_False;
842 *subexp = exp->_matches[n];
843 return TRex_True;
844 }
847 //########################################################################
848 //########################################################################
849 //## E N D R E G E X P
850 //########################################################################
851 //########################################################################
857 //########################################################################
858 //########################################################################
859 //## X M L
860 //########################################################################
861 //########################################################################
863 // Note: This mini-dom library comes from Pedro, another little project
864 // of mine.
866 typedef std::string String;
867 typedef unsigned int XMLCh;
870 class Namespace
871 {
872 public:
873 Namespace()
874 {}
876 Namespace(const String &prefixArg, const String &namespaceURIArg)
877 {
878 prefix = prefixArg;
879 namespaceURI = namespaceURIArg;
880 }
882 Namespace(const Namespace &other)
883 {
884 assign(other);
885 }
887 Namespace &operator=(const Namespace &other)
888 {
889 assign(other);
890 return *this;
891 }
893 virtual ~Namespace()
894 {}
896 virtual String getPrefix()
897 { return prefix; }
899 virtual String getNamespaceURI()
900 { return namespaceURI; }
902 protected:
904 void assign(const Namespace &other)
905 {
906 prefix = other.prefix;
907 namespaceURI = other.namespaceURI;
908 }
910 String prefix;
911 String namespaceURI;
913 };
915 class Attribute
916 {
917 public:
918 Attribute()
919 {}
921 Attribute(const String &nameArg, const String &valueArg)
922 {
923 name = nameArg;
924 value = valueArg;
925 }
927 Attribute(const Attribute &other)
928 {
929 assign(other);
930 }
932 Attribute &operator=(const Attribute &other)
933 {
934 assign(other);
935 return *this;
936 }
938 virtual ~Attribute()
939 {}
941 virtual String getName()
942 { return name; }
944 virtual String getValue()
945 { return value; }
947 protected:
949 void assign(const Attribute &other)
950 {
951 name = other.name;
952 value = other.value;
953 }
955 String name;
956 String value;
958 };
961 class Element
962 {
963 friend class Parser;
965 public:
966 Element()
967 {
968 init();
969 }
971 Element(const String &nameArg)
972 {
973 init();
974 name = nameArg;
975 }
977 Element(const String &nameArg, const String &valueArg)
978 {
979 init();
980 name = nameArg;
981 value = valueArg;
982 }
984 Element(const Element &other)
985 {
986 assign(other);
987 }
989 Element &operator=(const Element &other)
990 {
991 assign(other);
992 return *this;
993 }
995 virtual Element *clone();
997 virtual ~Element()
998 {
999 for (unsigned int i=0 ; i<children.size() ; i++)
1000 delete children[i];
1001 }
1003 virtual String getName()
1004 { return name; }
1006 virtual String getValue()
1007 { return value; }
1009 Element *getParent()
1010 { return parent; }
1012 std::vector<Element *> getChildren()
1013 { return children; }
1015 std::vector<Element *> findElements(const String &name);
1017 String getAttribute(const String &name);
1019 std::vector<Attribute> &getAttributes()
1020 { return attributes; }
1022 String getTagAttribute(const String &tagName, const String &attrName);
1024 String getTagValue(const String &tagName);
1026 void addChild(Element *child);
1028 void addAttribute(const String &name, const String &value);
1030 void addNamespace(const String &prefix, const String &namespaceURI);
1033 /**
1034 * Prettyprint an XML tree to an output stream. Elements are indented
1035 * according to element hierarchy.
1036 * @param f a stream to receive the output
1037 * @param elem the element to output
1038 */
1039 void writeIndented(FILE *f);
1041 /**
1042 * Prettyprint an XML tree to standard output. This is the equivalent of
1043 * writeIndented(stdout).
1044 * @param elem the element to output
1045 */
1046 void print();
1048 int getLine()
1049 { return line; }
1051 protected:
1053 void init()
1054 {
1055 parent = NULL;
1056 line = 0;
1057 }
1059 void assign(const Element &other)
1060 {
1061 parent = other.parent;
1062 children = other.children;
1063 attributes = other.attributes;
1064 namespaces = other.namespaces;
1065 name = other.name;
1066 value = other.value;
1067 line = other.line;
1068 }
1070 void findElementsRecursive(std::vector<Element *>&res, const String &name);
1072 void writeIndentedRecursive(FILE *f, int indent);
1074 Element *parent;
1076 std::vector<Element *>children;
1078 std::vector<Attribute> attributes;
1079 std::vector<Namespace> namespaces;
1081 String name;
1082 String value;
1084 int line;
1085 };
1091 class Parser
1092 {
1093 public:
1094 /**
1095 * Constructor
1096 */
1097 Parser()
1098 { init(); }
1100 virtual ~Parser()
1101 {}
1103 /**
1104 * Parse XML in a char buffer.
1105 * @param buf a character buffer to parse
1106 * @param pos position to start parsing
1107 * @param len number of chars, from pos, to parse.
1108 * @return a pointer to the root of the XML document;
1109 */
1110 Element *parse(const char *buf,int pos,int len);
1112 /**
1113 * Parse XML in a char buffer.
1114 * @param buf a character buffer to parse
1115 * @param pos position to start parsing
1116 * @param len number of chars, from pos, to parse.
1117 * @return a pointer to the root of the XML document;
1118 */
1119 Element *parse(const String &buf);
1121 /**
1122 * Parse a named XML file. The file is loaded like a data file;
1123 * the original format is not preserved.
1124 * @param fileName the name of the file to read
1125 * @return a pointer to the root of the XML document;
1126 */
1127 Element *parseFile(const String &fileName);
1129 /**
1130 * Utility method to preprocess a string for XML
1131 * output, escaping its entities.
1132 * @param str the string to encode
1133 */
1134 static String encode(const String &str);
1136 /**
1137 * Removes whitespace from beginning and end of a string
1138 */
1139 String trim(const String &s);
1141 private:
1143 void init()
1144 {
1145 keepGoing = true;
1146 currentNode = NULL;
1147 parselen = 0;
1148 parsebuf = NULL;
1149 currentPosition = 0;
1150 }
1152 int countLines(int begin, int end);
1154 void getLineAndColumn(int pos, int *lineNr, int *colNr);
1156 void error(const char *fmt, ...);
1158 int peek(int pos);
1160 int match(int pos, const char *text);
1162 int skipwhite(int p);
1164 int getWord(int p0, String &buf);
1166 int getQuoted(int p0, String &buf, int do_i_parse);
1168 int parseVersion(int p0);
1170 int parseDoctype(int p0);
1172 int parseElement(int p0, Element *par,int depth);
1174 Element *parse(XMLCh *buf,int pos,int len);
1176 bool keepGoing;
1177 Element *currentNode;
1178 int parselen;
1179 XMLCh *parsebuf;
1180 String cdatabuf;
1181 int currentPosition;
1182 };
1187 //########################################################################
1188 //# E L E M E N T
1189 //########################################################################
1191 Element *Element::clone()
1192 {
1193 Element *elem = new Element(name, value);
1194 elem->parent = parent;
1195 elem->attributes = attributes;
1196 elem->namespaces = namespaces;
1197 elem->line = line;
1199 std::vector<Element *>::iterator iter;
1200 for (iter = children.begin(); iter != children.end() ; iter++)
1201 {
1202 elem->addChild((*iter)->clone());
1203 }
1204 return elem;
1205 }
1208 void Element::findElementsRecursive(std::vector<Element *>&res, const String &name)
1209 {
1210 if (getName() == name)
1211 {
1212 res.push_back(this);
1213 }
1214 for (unsigned int i=0; i<children.size() ; i++)
1215 children[i]->findElementsRecursive(res, name);
1216 }
1218 std::vector<Element *> Element::findElements(const String &name)
1219 {
1220 std::vector<Element *> res;
1221 findElementsRecursive(res, name);
1222 return res;
1223 }
1225 String Element::getAttribute(const String &name)
1226 {
1227 for (unsigned int i=0 ; i<attributes.size() ; i++)
1228 if (attributes[i].getName() ==name)
1229 return attributes[i].getValue();
1230 return "";
1231 }
1233 String Element::getTagAttribute(const String &tagName, const String &attrName)
1234 {
1235 std::vector<Element *>elems = findElements(tagName);
1236 if (elems.size() <1)
1237 return "";
1238 String res = elems[0]->getAttribute(attrName);
1239 return res;
1240 }
1242 String Element::getTagValue(const String &tagName)
1243 {
1244 std::vector<Element *>elems = findElements(tagName);
1245 if (elems.size() <1)
1246 return "";
1247 String res = elems[0]->getValue();
1248 return res;
1249 }
1251 void Element::addChild(Element *child)
1252 {
1253 if (!child)
1254 return;
1255 child->parent = this;
1256 children.push_back(child);
1257 }
1260 void Element::addAttribute(const String &name, const String &value)
1261 {
1262 Attribute attr(name, value);
1263 attributes.push_back(attr);
1264 }
1266 void Element::addNamespace(const String &prefix, const String &namespaceURI)
1267 {
1268 Namespace ns(prefix, namespaceURI);
1269 namespaces.push_back(ns);
1270 }
1272 void Element::writeIndentedRecursive(FILE *f, int indent)
1273 {
1274 int i;
1275 if (!f)
1276 return;
1277 //Opening tag, and attributes
1278 for (i=0;i<indent;i++)
1279 fputc(' ',f);
1280 fprintf(f,"<%s",name.c_str());
1281 for (unsigned int i=0 ; i<attributes.size() ; i++)
1282 {
1283 fprintf(f," %s=\"%s\"",
1284 attributes[i].getName().c_str(),
1285 attributes[i].getValue().c_str());
1286 }
1287 for (unsigned int i=0 ; i<namespaces.size() ; i++)
1288 {
1289 fprintf(f," xmlns:%s=\"%s\"",
1290 namespaces[i].getPrefix().c_str(),
1291 namespaces[i].getNamespaceURI().c_str());
1292 }
1293 fprintf(f,">\n");
1295 //Between the tags
1296 if (value.size() > 0)
1297 {
1298 for (int i=0;i<indent;i++)
1299 fputc(' ', f);
1300 fprintf(f," %s\n", value.c_str());
1301 }
1303 for (unsigned int i=0 ; i<children.size() ; i++)
1304 children[i]->writeIndentedRecursive(f, indent+2);
1306 //Closing tag
1307 for (int i=0; i<indent; i++)
1308 fputc(' ',f);
1309 fprintf(f,"</%s>\n", name.c_str());
1310 }
1312 void Element::writeIndented(FILE *f)
1313 {
1314 writeIndentedRecursive(f, 0);
1315 }
1317 void Element::print()
1318 {
1319 writeIndented(stdout);
1320 }
1323 //########################################################################
1324 //# P A R S E R
1325 //########################################################################
1329 typedef struct
1330 {
1331 const char *escaped;
1332 char value;
1333 } EntityEntry;
1335 static EntityEntry entities[] =
1336 {
1337 { "&" , '&' },
1338 { "<" , '<' },
1339 { ">" , '>' },
1340 { "'", '\'' },
1341 { """, '"' },
1342 { NULL , '\0' }
1343 };
1347 /**
1348 * Removes whitespace from beginning and end of a string
1349 */
1350 String Parser::trim(const String &s)
1351 {
1352 if (s.size() < 1)
1353 return s;
1355 //Find first non-ws char
1356 unsigned int begin = 0;
1357 for ( ; begin < s.size() ; begin++)
1358 {
1359 if (!isspace(s[begin]))
1360 break;
1361 }
1363 //Find first non-ws char, going in reverse
1364 unsigned int end = s.size() - 1;
1365 for ( ; end > begin ; end--)
1366 {
1367 if (!isspace(s[end]))
1368 break;
1369 }
1370 //trace("begin:%d end:%d", begin, end);
1372 String res = s.substr(begin, end-begin+1);
1373 return res;
1374 }
1377 int Parser::countLines(int begin, int end)
1378 {
1379 int count = 0;
1380 for (int i=begin ; i<end ; i++)
1381 {
1382 XMLCh ch = parsebuf[i];
1383 if (ch == '\n' || ch == '\r')
1384 count++;
1385 }
1386 return count;
1387 }
1390 void Parser::getLineAndColumn(int pos, int *lineNr, int *colNr)
1391 {
1392 int line = 1;
1393 int col = 1;
1394 for (long i=0 ; i<pos ; i++)
1395 {
1396 XMLCh ch = parsebuf[i];
1397 if (ch == '\n' || ch == '\r')
1398 {
1399 col = 0;
1400 line ++;
1401 }
1402 else
1403 col++;
1404 }
1405 *lineNr = line;
1406 *colNr = col;
1408 }
1411 void Parser::error(const char *fmt, ...)
1412 {
1413 int lineNr;
1414 int colNr;
1415 getLineAndColumn(currentPosition, &lineNr, &colNr);
1416 va_list args;
1417 fprintf(stderr, "xml error at line %d, column %d:", lineNr, colNr);
1418 va_start(args,fmt);
1419 vfprintf(stderr,fmt,args);
1420 va_end(args) ;
1421 fprintf(stderr, "\n");
1422 }
1426 int Parser::peek(int pos)
1427 {
1428 if (pos >= parselen)
1429 return -1;
1430 currentPosition = pos;
1431 int ch = parsebuf[pos];
1432 //printf("ch:%c\n", ch);
1433 return ch;
1434 }
1438 String Parser::encode(const String &str)
1439 {
1440 String ret;
1441 for (unsigned int i=0 ; i<str.size() ; i++)
1442 {
1443 XMLCh ch = (XMLCh)str[i];
1444 if (ch == '&')
1445 ret.append("&");
1446 else if (ch == '<')
1447 ret.append("<");
1448 else if (ch == '>')
1449 ret.append(">");
1450 else if (ch == '\'')
1451 ret.append("'");
1452 else if (ch == '"')
1453 ret.append(""");
1454 else
1455 ret.push_back(ch);
1457 }
1458 return ret;
1459 }
1462 int Parser::match(int p0, const char *text)
1463 {
1464 int p = p0;
1465 while (*text)
1466 {
1467 if (peek(p) != *text)
1468 return p0;
1469 p++; text++;
1470 }
1471 return p;
1472 }
1476 int Parser::skipwhite(int p)
1477 {
1479 while (p<parselen)
1480 {
1481 int p2 = match(p, "<!--");
1482 if (p2 > p)
1483 {
1484 p = p2;
1485 while (p<parselen)
1486 {
1487 p2 = match(p, "-->");
1488 if (p2 > p)
1489 {
1490 p = p2;
1491 break;
1492 }
1493 p++;
1494 }
1495 }
1496 XMLCh b = peek(p);
1497 if (!isspace(b))
1498 break;
1499 p++;
1500 }
1501 return p;
1502 }
1504 /* modify this to allow all chars for an element or attribute name*/
1505 int Parser::getWord(int p0, String &buf)
1506 {
1507 int p = p0;
1508 while (p<parselen)
1509 {
1510 XMLCh b = peek(p);
1511 if (b<=' ' || b=='/' || b=='>' || b=='=')
1512 break;
1513 buf.push_back(b);
1514 p++;
1515 }
1516 return p;
1517 }
1519 int Parser::getQuoted(int p0, String &buf, int do_i_parse)
1520 {
1522 int p = p0;
1523 if (peek(p) != '"' && peek(p) != '\'')
1524 return p0;
1525 p++;
1527 while ( p<parselen )
1528 {
1529 XMLCh b = peek(p);
1530 if (b=='"' || b=='\'')
1531 break;
1532 if (b=='&' && do_i_parse)
1533 {
1534 bool found = false;
1535 for (EntityEntry *ee = entities ; ee->value ; ee++)
1536 {
1537 int p2 = match(p, ee->escaped);
1538 if (p2>p)
1539 {
1540 buf.push_back(ee->value);
1541 p = p2;
1542 found = true;
1543 break;
1544 }
1545 }
1546 if (!found)
1547 {
1548 error("unterminated entity");
1549 return false;
1550 }
1551 }
1552 else
1553 {
1554 buf.push_back(b);
1555 p++;
1556 }
1557 }
1558 return p;
1559 }
1561 int Parser::parseVersion(int p0)
1562 {
1563 //printf("### parseVersion: %d\n", p0);
1565 int p = p0;
1567 p = skipwhite(p0);
1569 if (peek(p) != '<')
1570 return p0;
1572 p++;
1573 if (p>=parselen || peek(p)!='?')
1574 return p0;
1576 p++;
1578 String buf;
1580 while (p<parselen)
1581 {
1582 XMLCh ch = peek(p);
1583 if (ch=='?')
1584 {
1585 p++;
1586 break;
1587 }
1588 buf.push_back(ch);
1589 p++;
1590 }
1592 if (peek(p) != '>')
1593 return p0;
1594 p++;
1596 //printf("Got version:%s\n",buf.c_str());
1597 return p;
1598 }
1600 int Parser::parseDoctype(int p0)
1601 {
1602 //printf("### parseDoctype: %d\n", p0);
1604 int p = p0;
1605 p = skipwhite(p);
1607 if (p>=parselen || peek(p)!='<')
1608 return p0;
1610 p++;
1612 if (peek(p)!='!' || peek(p+1)=='-')
1613 return p0;
1614 p++;
1616 String buf;
1617 while (p<parselen)
1618 {
1619 XMLCh ch = peek(p);
1620 if (ch=='>')
1621 {
1622 p++;
1623 break;
1624 }
1625 buf.push_back(ch);
1626 p++;
1627 }
1629 //printf("Got doctype:%s\n",buf.c_str());
1630 return p;
1631 }
1635 int Parser::parseElement(int p0, Element *par,int lineNr)
1636 {
1638 int p = p0;
1640 int p2 = p;
1642 p = skipwhite(p);
1644 //## Get open tag
1645 XMLCh ch = peek(p);
1646 if (ch!='<')
1647 return p0;
1649 //int line, col;
1650 //getLineAndColumn(p, &line, &col);
1652 p++;
1654 String openTagName;
1655 p = skipwhite(p);
1656 p = getWord(p, openTagName);
1657 //printf("####tag :%s\n", openTagName.c_str());
1658 p = skipwhite(p);
1660 //Add element to tree
1661 Element *n = new Element(openTagName);
1662 n->line = lineNr + countLines(p0, p);
1663 n->parent = par;
1664 par->addChild(n);
1666 // Get attributes
1667 if (peek(p) != '>')
1668 {
1669 while (p<parselen)
1670 {
1671 p = skipwhite(p);
1672 ch = peek(p);
1673 //printf("ch:%c\n",ch);
1674 if (ch=='>')
1675 break;
1676 else if (ch=='/' && p<parselen+1)
1677 {
1678 p++;
1679 p = skipwhite(p);
1680 ch = peek(p);
1681 if (ch=='>')
1682 {
1683 p++;
1684 //printf("quick close\n");
1685 return p;
1686 }
1687 }
1688 String attrName;
1689 p2 = getWord(p, attrName);
1690 if (p2==p)
1691 break;
1692 //printf("name:%s",buf);
1693 p=p2;
1694 p = skipwhite(p);
1695 ch = peek(p);
1696 //printf("ch:%c\n",ch);
1697 if (ch!='=')
1698 break;
1699 p++;
1700 p = skipwhite(p);
1701 // ch = parsebuf[p];
1702 // printf("ch:%c\n",ch);
1703 String attrVal;
1704 p2 = getQuoted(p, attrVal, true);
1705 p=p2+1;
1706 //printf("name:'%s' value:'%s'\n",attrName.c_str(),attrVal.c_str());
1707 char *namestr = (char *)attrName.c_str();
1708 if (strncmp(namestr, "xmlns:", 6)==0)
1709 n->addNamespace(attrName, attrVal);
1710 else
1711 n->addAttribute(attrName, attrVal);
1712 }
1713 }
1715 bool cdata = false;
1717 p++;
1718 // ### Get intervening data ### */
1719 String data;
1720 while (p<parselen)
1721 {
1722 //# COMMENT
1723 p2 = match(p, "<!--");
1724 if (!cdata && p2>p)
1725 {
1726 p = p2;
1727 while (p<parselen)
1728 {
1729 p2 = match(p, "-->");
1730 if (p2 > p)
1731 {
1732 p = p2;
1733 break;
1734 }
1735 p++;
1736 }
1737 }
1739 ch = peek(p);
1740 //# END TAG
1741 if (ch=='<' && !cdata && peek(p+1)=='/')
1742 {
1743 break;
1744 }
1745 //# CDATA
1746 p2 = match(p, "<![CDATA[");
1747 if (p2 > p)
1748 {
1749 cdata = true;
1750 p = p2;
1751 continue;
1752 }
1754 //# CHILD ELEMENT
1755 if (ch == '<')
1756 {
1757 p2 = parseElement(p, n, lineNr + countLines(p0, p));
1758 if (p2 == p)
1759 {
1760 /*
1761 printf("problem on element:%s. p2:%d p:%d\n",
1762 openTagName.c_str(), p2, p);
1763 */
1764 return p0;
1765 }
1766 p = p2;
1767 continue;
1768 }
1769 //# ENTITY
1770 if (ch=='&' && !cdata)
1771 {
1772 bool found = false;
1773 for (EntityEntry *ee = entities ; ee->value ; ee++)
1774 {
1775 int p2 = match(p, ee->escaped);
1776 if (p2>p)
1777 {
1778 data.push_back(ee->value);
1779 p = p2;
1780 found = true;
1781 break;
1782 }
1783 }
1784 if (!found)
1785 {
1786 error("unterminated entity");
1787 return -1;
1788 }
1789 continue;
1790 }
1792 //# NONE OF THE ABOVE
1793 data.push_back(ch);
1794 p++;
1795 }/*while*/
1798 n->value = data;
1799 //printf("%d : data:%s\n",p,data.c_str());
1801 //## Get close tag
1802 p = skipwhite(p);
1803 ch = peek(p);
1804 if (ch != '<')
1805 {
1806 error("no < for end tag\n");
1807 return p0;
1808 }
1809 p++;
1810 ch = peek(p);
1811 if (ch != '/')
1812 {
1813 error("no / on end tag");
1814 return p0;
1815 }
1816 p++;
1817 ch = peek(p);
1818 p = skipwhite(p);
1819 String closeTagName;
1820 p = getWord(p, closeTagName);
1821 if (openTagName != closeTagName)
1822 {
1823 error("Mismatched closing tag. Expected </%S>. Got '%S'.",
1824 openTagName.c_str(), closeTagName.c_str());
1825 return p0;
1826 }
1827 p = skipwhite(p);
1828 if (peek(p) != '>')
1829 {
1830 error("no > on end tag for '%s'", closeTagName.c_str());
1831 return p0;
1832 }
1833 p++;
1834 // printf("close element:%s\n",closeTagName.c_str());
1835 p = skipwhite(p);
1836 return p;
1837 }
1842 Element *Parser::parse(XMLCh *buf,int pos,int len)
1843 {
1844 parselen = len;
1845 parsebuf = buf;
1846 Element *rootNode = new Element("root");
1847 pos = parseVersion(pos);
1848 pos = parseDoctype(pos);
1849 pos = parseElement(pos, rootNode, 1);
1850 return rootNode;
1851 }
1854 Element *Parser::parse(const char *buf, int pos, int len)
1855 {
1856 XMLCh *charbuf = new XMLCh[len + 1];
1857 long i = 0;
1858 for ( ; i < len ; i++)
1859 charbuf[i] = (XMLCh)buf[i];
1860 charbuf[i] = '\0';
1862 Element *n = parse(charbuf, pos, len);
1863 delete[] charbuf;
1864 return n;
1865 }
1867 Element *Parser::parse(const String &buf)
1868 {
1869 long len = (long)buf.size();
1870 XMLCh *charbuf = new XMLCh[len + 1];
1871 long i = 0;
1872 for ( ; i < len ; i++)
1873 charbuf[i] = (XMLCh)buf[i];
1874 charbuf[i] = '\0';
1876 Element *n = parse(charbuf, 0, len);
1877 delete[] charbuf;
1878 return n;
1879 }
1881 Element *Parser::parseFile(const String &fileName)
1882 {
1884 //##### LOAD INTO A CHAR BUF, THEN CONVERT TO XMLCh
1885 FILE *f = fopen(fileName.c_str(), "rb");
1886 if (!f)
1887 return NULL;
1889 struct stat statBuf;
1890 if (fstat(fileno(f),&statBuf)<0)
1891 {
1892 fclose(f);
1893 return NULL;
1894 }
1895 long filelen = statBuf.st_size;
1897 //printf("length:%d\n",filelen);
1898 XMLCh *charbuf = new XMLCh[filelen + 1];
1899 for (XMLCh *p=charbuf ; !feof(f) ; p++)
1900 {
1901 *p = (XMLCh)fgetc(f);
1902 }
1903 fclose(f);
1904 charbuf[filelen] = '\0';
1907 /*
1908 printf("nrbytes:%d\n",wc_count);
1909 printf("buf:%ls\n======\n",charbuf);
1910 */
1911 Element *n = parse(charbuf, 0, filelen);
1912 delete[] charbuf;
1913 return n;
1914 }
1916 //########################################################################
1917 //########################################################################
1918 //## E N D X M L
1919 //########################################################################
1920 //########################################################################
1927 //########################################################################
1928 //########################################################################
1929 //## U R I
1930 //########################################################################
1931 //########################################################################
1933 //This would normally be a call to a UNICODE function
1934 #define isLetter(x) isalpha(x)
1936 /**
1937 * A class that implements the W3C URI resource reference.
1938 */
1939 class URI
1940 {
1941 public:
1943 typedef enum
1944 {
1945 SCHEME_NONE =0,
1946 SCHEME_DATA,
1947 SCHEME_HTTP,
1948 SCHEME_HTTPS,
1949 SCHEME_FTP,
1950 SCHEME_FILE,
1951 SCHEME_LDAP,
1952 SCHEME_MAILTO,
1953 SCHEME_NEWS,
1954 SCHEME_TELNET
1955 } SchemeTypes;
1957 /**
1958 *
1959 */
1960 URI()
1961 {
1962 init();
1963 }
1965 /**
1966 *
1967 */
1968 URI(const String &str)
1969 {
1970 init();
1971 parse(str);
1972 }
1975 /**
1976 *
1977 */
1978 URI(const char *str)
1979 {
1980 init();
1981 String domStr = str;
1982 parse(domStr);
1983 }
1986 /**
1987 *
1988 */
1989 URI(const URI &other)
1990 {
1991 init();
1992 assign(other);
1993 }
1996 /**
1997 *
1998 */
1999 URI &operator=(const URI &other)
2000 {
2001 init();
2002 assign(other);
2003 return *this;
2004 }
2007 /**
2008 *
2009 */
2010 virtual ~URI()
2011 {}
2015 /**
2016 *
2017 */
2018 virtual bool parse(const String &str);
2020 /**
2021 *
2022 */
2023 virtual String toString() const;
2025 /**
2026 *
2027 */
2028 virtual int getScheme() const;
2030 /**
2031 *
2032 */
2033 virtual String getSchemeStr() const;
2035 /**
2036 *
2037 */
2038 virtual String getAuthority() const;
2040 /**
2041 * Same as getAuthority, but if the port has been specified
2042 * as host:port , the port will not be included
2043 */
2044 virtual String getHost() const;
2046 /**
2047 *
2048 */
2049 virtual int getPort() const;
2051 /**
2052 *
2053 */
2054 virtual String getPath() const;
2056 /**
2057 *
2058 */
2059 virtual String getNativePath() const;
2061 /**
2062 *
2063 */
2064 virtual bool isAbsolute() const;
2066 /**
2067 *
2068 */
2069 virtual bool isOpaque() const;
2071 /**
2072 *
2073 */
2074 virtual String getQuery() const;
2076 /**
2077 *
2078 */
2079 virtual String getFragment() const;
2081 /**
2082 *
2083 */
2084 virtual URI resolve(const URI &other) const;
2086 /**
2087 *
2088 */
2089 virtual void normalize();
2091 private:
2093 /**
2094 *
2095 */
2096 void init()
2097 {
2098 parsebuf = NULL;
2099 parselen = 0;
2100 scheme = SCHEME_NONE;
2101 schemeStr = "";
2102 port = 0;
2103 authority = "";
2104 path = "";
2105 absolute = false;
2106 opaque = false;
2107 query = "";
2108 fragment = "";
2109 }
2112 /**
2113 *
2114 */
2115 void assign(const URI &other)
2116 {
2117 scheme = other.scheme;
2118 schemeStr = other.schemeStr;
2119 authority = other.authority;
2120 port = other.port;
2121 path = other.path;
2122 absolute = other.absolute;
2123 opaque = other.opaque;
2124 query = other.query;
2125 fragment = other.fragment;
2126 }
2128 int scheme;
2130 String schemeStr;
2132 String authority;
2134 bool portSpecified;
2136 int port;
2138 String path;
2140 bool absolute;
2142 bool opaque;
2144 String query;
2146 String fragment;
2148 void error(const char *fmt, ...);
2150 void trace(const char *fmt, ...);
2153 int peek(int p);
2155 int match(int p, const char *key);
2157 int parseScheme(int p);
2159 int parseHierarchicalPart(int p0);
2161 int parseQuery(int p0);
2163 int parseFragment(int p0);
2165 int parse(int p);
2167 char *parsebuf;
2169 int parselen;
2171 };
2175 typedef struct
2176 {
2177 int ival;
2178 const char *sval;
2179 int port;
2180 } LookupEntry;
2182 LookupEntry schemes[] =
2183 {
2184 { URI::SCHEME_DATA, "data:", 0 },
2185 { URI::SCHEME_HTTP, "http:", 80 },
2186 { URI::SCHEME_HTTPS, "https:", 443 },
2187 { URI::SCHEME_FTP, "ftp", 12 },
2188 { URI::SCHEME_FILE, "file:", 0 },
2189 { URI::SCHEME_LDAP, "ldap:", 123 },
2190 { URI::SCHEME_MAILTO, "mailto:", 25 },
2191 { URI::SCHEME_NEWS, "news:", 117 },
2192 { URI::SCHEME_TELNET, "telnet:", 23 },
2193 { 0, NULL, 0 }
2194 };
2197 String URI::toString() const
2198 {
2199 String str = schemeStr;
2200 if (authority.size() > 0)
2201 {
2202 str.append("//");
2203 str.append(authority);
2204 }
2205 str.append(path);
2206 if (query.size() > 0)
2207 {
2208 str.append("?");
2209 str.append(query);
2210 }
2211 if (fragment.size() > 0)
2212 {
2213 str.append("#");
2214 str.append(fragment);
2215 }
2216 return str;
2217 }
2220 int URI::getScheme() const
2221 {
2222 return scheme;
2223 }
2225 String URI::getSchemeStr() const
2226 {
2227 return schemeStr;
2228 }
2231 String URI::getAuthority() const
2232 {
2233 String ret = authority;
2234 if (portSpecified && port>=0)
2235 {
2236 char buf[7];
2237 snprintf(buf, 6, ":%6d", port);
2238 ret.append(buf);
2239 }
2240 return ret;
2241 }
2243 String URI::getHost() const
2244 {
2245 return authority;
2246 }
2248 int URI::getPort() const
2249 {
2250 return port;
2251 }
2254 String URI::getPath() const
2255 {
2256 return path;
2257 }
2259 String URI::getNativePath() const
2260 {
2261 String npath;
2262 #ifdef __WIN32__
2263 unsigned int firstChar = 0;
2264 if (path.size() >= 3)
2265 {
2266 if (path[0] == '/' &&
2267 isLetter(path[1]) &&
2268 path[2] == ':')
2269 firstChar++;
2270 }
2271 for (unsigned int i=firstChar ; i<path.size() ; i++)
2272 {
2273 XMLCh ch = (XMLCh) path[i];
2274 if (ch == '/')
2275 npath.push_back((XMLCh)'\\');
2276 else
2277 npath.push_back(ch);
2278 }
2279 #else
2280 npath = path;
2281 #endif
2282 return npath;
2283 }
2286 bool URI::isAbsolute() const
2287 {
2288 return absolute;
2289 }
2291 bool URI::isOpaque() const
2292 {
2293 return opaque;
2294 }
2297 String URI::getQuery() const
2298 {
2299 return query;
2300 }
2303 String URI::getFragment() const
2304 {
2305 return fragment;
2306 }
2309 URI URI::resolve(const URI &other) const
2310 {
2311 //### According to w3c, this is handled in 3 cases
2313 //## 1
2314 if (opaque || other.isAbsolute())
2315 return other;
2317 //## 2
2318 if (other.fragment.size() > 0 &&
2319 other.path.size() == 0 &&
2320 other.scheme == SCHEME_NONE &&
2321 other.authority.size() == 0 &&
2322 other.query.size() == 0 )
2323 {
2324 URI fragUri = *this;
2325 fragUri.fragment = other.fragment;
2326 return fragUri;
2327 }
2329 //## 3 http://www.ietf.org/rfc/rfc2396.txt, section 5.2
2330 URI newUri;
2331 //# 3.1
2332 newUri.scheme = scheme;
2333 newUri.schemeStr = schemeStr;
2334 newUri.query = other.query;
2335 newUri.fragment = other.fragment;
2336 if (other.authority.size() > 0)
2337 {
2338 //# 3.2
2339 if (absolute || other.absolute)
2340 newUri.absolute = true;
2341 newUri.authority = other.authority;
2342 newUri.port = other.port;//part of authority
2343 newUri.path = other.path;
2344 }
2345 else
2346 {
2347 //# 3.3
2348 if (other.absolute)
2349 {
2350 newUri.absolute = true;
2351 newUri.path = other.path;
2352 }
2353 else
2354 {
2355 unsigned int pos = path.find_last_of('/');
2356 if (pos != path.npos)
2357 {
2358 String tpath = path.substr(0, pos+1);
2359 tpath.append(other.path);
2360 newUri.path = tpath;
2361 }
2362 else
2363 newUri.path = other.path;
2364 }
2365 }
2367 newUri.normalize();
2368 return newUri;
2369 }
2373 /**
2374 * This follows the Java URI algorithm:
2375 * 1. All "." segments are removed.
2376 * 2. If a ".." segment is preceded by a non-".." segment
2377 * then both of these segments are removed. This step
2378 * is repeated until it is no longer applicable.
2379 * 3. If the path is relative, and if its first segment
2380 * contains a colon character (':'), then a "." segment
2381 * is prepended. This prevents a relative URI with a path
2382 * such as "a:b/c/d" from later being re-parsed as an
2383 * opaque URI with a scheme of "a" and a scheme-specific
2384 * part of "b/c/d". (Deviation from RFC 2396)
2385 */
2386 void URI::normalize()
2387 {
2388 std::vector<String> segments;
2390 //## Collect segments
2391 if (path.size()<2)
2392 return;
2393 bool abs = false;
2394 unsigned int pos=0;
2395 if (path[0]=='/')
2396 {
2397 abs = true;
2398 pos++;
2399 }
2400 while (pos < path.size())
2401 {
2402 unsigned int pos2 = path.find('/', pos);
2403 if (pos2==path.npos)
2404 {
2405 String seg = path.substr(pos);
2406 //printf("last segment:%s\n", seg.c_str());
2407 segments.push_back(seg);
2408 break;
2409 }
2410 if (pos2>pos)
2411 {
2412 String seg = path.substr(pos, pos2-pos);
2413 //printf("segment:%s\n", seg.c_str());
2414 segments.push_back(seg);
2415 }
2416 pos = pos2;
2417 pos++;
2418 }
2420 //## Clean up (normalize) segments
2421 bool edited = false;
2422 std::vector<String>::iterator iter;
2423 for (iter=segments.begin() ; iter!=segments.end() ; )
2424 {
2425 String s = *iter;
2426 if (s == ".")
2427 {
2428 iter = segments.erase(iter);
2429 edited = true;
2430 }
2431 else if (s == ".." &&
2432 iter != segments.begin() &&
2433 *(iter-1) != "..")
2434 {
2435 iter--; //back up, then erase two entries
2436 iter = segments.erase(iter);
2437 iter = segments.erase(iter);
2438 edited = true;
2439 }
2440 else
2441 iter++;
2442 }
2444 //## Rebuild path, if necessary
2445 if (edited)
2446 {
2447 path.clear();
2448 if (abs)
2449 {
2450 path.append("/");
2451 }
2452 std::vector<String>::iterator iter;
2453 for (iter=segments.begin() ; iter!=segments.end() ; iter++)
2454 {
2455 if (iter != segments.begin())
2456 path.append("/");
2457 path.append(*iter);
2458 }
2459 }
2461 }
2465 //#########################################################################
2466 //# M E S S A G E S
2467 //#########################################################################
2469 void URI::error(const char *fmt, ...)
2470 {
2471 va_list args;
2472 fprintf(stderr, "URI error: ");
2473 va_start(args, fmt);
2474 vfprintf(stderr, fmt, args);
2475 va_end(args);
2476 fprintf(stderr, "\n");
2477 }
2479 void URI::trace(const char *fmt, ...)
2480 {
2481 va_list args;
2482 fprintf(stdout, "URI: ");
2483 va_start(args, fmt);
2484 vfprintf(stdout, fmt, args);
2485 va_end(args);
2486 fprintf(stdout, "\n");
2487 }
2492 //#########################################################################
2493 //# P A R S I N G
2494 //#########################################################################
2498 int URI::peek(int p)
2499 {
2500 if (p<0 || p>=parselen)
2501 return -1;
2502 return parsebuf[p];
2503 }
2507 int URI::match(int p0, const char *key)
2508 {
2509 int p = p0;
2510 while (p < parselen)
2511 {
2512 if (*key == '\0')
2513 return p;
2514 else if (*key != parsebuf[p])
2515 break;
2516 p++; key++;
2517 }
2518 return p0;
2519 }
2521 //#########################################################################
2522 //# Parsing is performed according to:
2523 //# http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#components
2524 //#########################################################################
2526 int URI::parseScheme(int p0)
2527 {
2528 int p = p0;
2529 for (LookupEntry *entry = schemes; entry->sval ; entry++)
2530 {
2531 int p2 = match(p, entry->sval);
2532 if (p2 > p)
2533 {
2534 schemeStr = entry->sval;
2535 scheme = entry->ival;
2536 port = entry->port;
2537 p = p2;
2538 return p;
2539 }
2540 }
2542 return p;
2543 }
2546 int URI::parseHierarchicalPart(int p0)
2547 {
2548 int p = p0;
2549 int ch;
2551 //# Authority field (host and port, for example)
2552 int p2 = match(p, "//");
2553 if (p2 > p)
2554 {
2555 p = p2;
2556 portSpecified = false;
2557 String portStr;
2558 while (p < parselen)
2559 {
2560 ch = peek(p);
2561 if (ch == '/')
2562 break;
2563 else if (ch == ':')
2564 portSpecified = true;
2565 else if (portSpecified)
2566 portStr.push_back((XMLCh)ch);
2567 else
2568 authority.push_back((XMLCh)ch);
2569 p++;
2570 }
2571 if (portStr.size() > 0)
2572 {
2573 char *pstr = (char *)portStr.c_str();
2574 char *endStr;
2575 long val = strtol(pstr, &endStr, 10);
2576 if (endStr > pstr) //successful parse?
2577 port = val;
2578 }
2579 }
2581 //# Are we absolute?
2582 ch = peek(p);
2583 if (isLetter(ch) && peek(p+1)==':')
2584 {
2585 absolute = true;
2586 path.push_back((XMLCh)'/');
2587 }
2588 else if (ch == '/')
2589 {
2590 absolute = true;
2591 if (p>p0) //in other words, if '/' is not the first char
2592 opaque = true;
2593 path.push_back((XMLCh)ch);
2594 p++;
2595 }
2597 while (p < parselen)
2598 {
2599 ch = peek(p);
2600 if (ch == '?' || ch == '#')
2601 break;
2602 path.push_back((XMLCh)ch);
2603 p++;
2604 }
2606 return p;
2607 }
2609 int URI::parseQuery(int p0)
2610 {
2611 int p = p0;
2612 int ch = peek(p);
2613 if (ch != '?')
2614 return p0;
2616 p++;
2617 while (p < parselen)
2618 {
2619 ch = peek(p);
2620 if (ch == '#')
2621 break;
2622 query.push_back((XMLCh)ch);
2623 p++;
2624 }
2627 return p;
2628 }
2630 int URI::parseFragment(int p0)
2631 {
2633 int p = p0;
2634 int ch = peek(p);
2635 if (ch != '#')
2636 return p0;
2638 p++;
2639 while (p < parselen)
2640 {
2641 ch = peek(p);
2642 if (ch == '?')
2643 break;
2644 fragment.push_back((XMLCh)ch);
2645 p++;
2646 }
2649 return p;
2650 }
2653 int URI::parse(int p0)
2654 {
2656 int p = p0;
2658 int p2 = parseScheme(p);
2659 if (p2 < 0)
2660 {
2661 error("Scheme");
2662 return -1;
2663 }
2664 p = p2;
2667 p2 = parseHierarchicalPart(p);
2668 if (p2 < 0)
2669 {
2670 error("Hierarchical part");
2671 return -1;
2672 }
2673 p = p2;
2675 p2 = parseQuery(p);
2676 if (p2 < 0)
2677 {
2678 error("Query");
2679 return -1;
2680 }
2681 p = p2;
2684 p2 = parseFragment(p);
2685 if (p2 < 0)
2686 {
2687 error("Fragment");
2688 return -1;
2689 }
2690 p = p2;
2692 return p;
2694 }
2698 bool URI::parse(const String &str)
2699 {
2700 init();
2702 parselen = str.size();
2704 String tmp;
2705 for (unsigned int i=0 ; i<str.size() ; i++)
2706 {
2707 XMLCh ch = (XMLCh) str[i];
2708 if (ch == '\\')
2709 tmp.push_back((XMLCh)'/');
2710 else
2711 tmp.push_back(ch);
2712 }
2713 parsebuf = (char *) tmp.c_str();
2716 int p = parse(0);
2717 normalize();
2719 if (p < 0)
2720 {
2721 error("Syntax error");
2722 return false;
2723 }
2725 //printf("uri:%s\n", toString().c_str());
2726 //printf("path:%s\n", path.c_str());
2728 return true;
2730 }
2739 //########################################################################
2740 //########################################################################
2741 //## M A K E
2742 //########################################################################
2743 //########################################################################
2745 //########################################################################
2746 //# Stat cache to speed up stat requests
2747 //########################################################################
2748 struct StatResult {
2749 int result;
2750 struct stat statInfo;
2751 };
2752 typedef std::map<String, StatResult> statCacheType;
2753 static statCacheType statCache;
2754 static int cachedStat(const String &f, struct stat *s) {
2755 //printf("Stat path: %s\n", f.c_str());
2756 std::pair<statCacheType::iterator, bool> result = statCache.insert(statCacheType::value_type(f, StatResult()));
2757 if (result.second) {
2758 result.first->second.result = stat(f.c_str(), &(result.first->second.statInfo));
2759 }
2760 *s = result.first->second.statInfo;
2761 return result.first->second.result;
2762 }
2763 static void removeFromStatCache(const String f) {
2764 //printf("Removing from cache: %s\n", f.c_str());
2765 statCache.erase(f);
2766 }
2768 //########################################################################
2769 //# Dir cache to speed up dir requests
2770 //########################################################################
2771 /*struct DirListing {
2772 bool available;
2773 std::vector<String> files;
2774 std::vector<String> dirs;
2775 };
2776 typedef std::map<String, DirListing > dirCacheType;
2777 static dirCacheType dirCache;
2778 static const DirListing &cachedDir(String fullDir)
2779 {
2780 String dirNative = getNativePath(fullDir);
2781 std::pair<dirCacheType::iterator,bool> result = dirCache.insert(dirCacheType::value_type(dirNative, DirListing()));
2782 if (result.second) {
2783 DIR *dir = opendir(dirNative.c_str());
2784 if (!dir)
2785 {
2786 error("Could not open directory %s : %s",
2787 dirNative.c_str(), strerror(errno));
2788 result.first->second.available = false;
2789 }
2790 else
2791 {
2792 result.first->second.available = true;
2793 while (true)
2794 {
2795 struct dirent *de = readdir(dir);
2796 if (!de)
2797 break;
2799 //Get the directory member name
2800 String s = de->d_name;
2801 if (s.size() == 0 || s[0] == '.')
2802 continue;
2803 String childName;
2804 if (dirName.size()>0)
2805 {
2806 childName.append(dirName);
2807 childName.append("/");
2808 }
2809 childName.append(s);
2810 String fullChild = baseDir;
2811 fullChild.append("/");
2812 fullChild.append(childName);
2814 if (isDirectory(fullChild))
2815 {
2816 //trace("directory: %s", childName.c_str());
2817 if (!listFiles(baseDir, childName, res))
2818 return false;
2819 continue;
2820 }
2821 else if (!isRegularFile(fullChild))
2822 {
2823 error("unknown file:%s", childName.c_str());
2824 return false;
2825 }
2827 //all done!
2828 res.push_back(childName);
2830 }
2831 closedir(dir);
2832 }
2833 }
2834 return result.first->second;
2835 }*/
2837 //########################################################################
2838 //# F I L E S E T
2839 //########################################################################
2840 /**
2841 * This is the descriptor for a <fileset> item
2842 */
2843 class FileSet
2844 {
2845 public:
2847 /**
2848 *
2849 */
2850 FileSet()
2851 {}
2853 /**
2854 *
2855 */
2856 FileSet(const FileSet &other)
2857 { assign(other); }
2859 /**
2860 *
2861 */
2862 FileSet &operator=(const FileSet &other)
2863 { assign(other); return *this; }
2865 /**
2866 *
2867 */
2868 virtual ~FileSet()
2869 {}
2871 /**
2872 *
2873 */
2874 String getDirectory() const
2875 { return directory; }
2877 /**
2878 *
2879 */
2880 void setDirectory(const String &val)
2881 { directory = val; }
2883 /**
2884 *
2885 */
2886 void setFiles(const std::vector<String> &val)
2887 { files = val; }
2889 /**
2890 *
2891 */
2892 std::vector<String> getFiles() const
2893 { return files; }
2895 /**
2896 *
2897 */
2898 void setIncludes(const std::vector<String> &val)
2899 { includes = val; }
2901 /**
2902 *
2903 */
2904 std::vector<String> getIncludes() const
2905 { return includes; }
2907 /**
2908 *
2909 */
2910 void setExcludes(const std::vector<String> &val)
2911 { excludes = val; }
2913 /**
2914 *
2915 */
2916 std::vector<String> getExcludes() const
2917 { return excludes; }
2919 /**
2920 *
2921 */
2922 unsigned int size() const
2923 { return files.size(); }
2925 /**
2926 *
2927 */
2928 String operator[](int index) const
2929 { return files[index]; }
2931 /**
2932 *
2933 */
2934 void clear()
2935 {
2936 directory = "";
2937 files.clear();
2938 includes.clear();
2939 excludes.clear();
2940 }
2943 private:
2945 void assign(const FileSet &other)
2946 {
2947 directory = other.directory;
2948 files = other.files;
2949 includes = other.includes;
2950 excludes = other.excludes;
2951 }
2953 String directory;
2954 std::vector<String> files;
2955 std::vector<String> includes;
2956 std::vector<String> excludes;
2957 };
2960 //########################################################################
2961 //# F I L E L I S T
2962 //########################################################################
2963 /**
2964 * This is a simpler, explicitly-named list of files
2965 */
2966 class FileList
2967 {
2968 public:
2970 /**
2971 *
2972 */
2973 FileList()
2974 {}
2976 /**
2977 *
2978 */
2979 FileList(const FileList &other)
2980 { assign(other); }
2982 /**
2983 *
2984 */
2985 FileList &operator=(const FileList &other)
2986 { assign(other); return *this; }
2988 /**
2989 *
2990 */
2991 virtual ~FileList()
2992 {}
2994 /**
2995 *
2996 */
2997 String getDirectory()
2998 { return directory; }
3000 /**
3001 *
3002 */
3003 void setDirectory(const String &val)
3004 { directory = val; }
3006 /**
3007 *
3008 */
3009 void setFiles(const std::vector<String> &val)
3010 { files = val; }
3012 /**
3013 *
3014 */
3015 std::vector<String> getFiles()
3016 { return files; }
3018 /**
3019 *
3020 */
3021 unsigned int size()
3022 { return files.size(); }
3024 /**
3025 *
3026 */
3027 String operator[](int index)
3028 { return files[index]; }
3030 /**
3031 *
3032 */
3033 void clear()
3034 {
3035 directory = "";
3036 files.clear();
3037 }
3040 private:
3042 void assign(const FileList &other)
3043 {
3044 directory = other.directory;
3045 files = other.files;
3046 }
3048 String directory;
3049 std::vector<String> files;
3050 };
3055 //########################################################################
3056 //# M A K E B A S E
3057 //########################################################################
3058 /**
3059 * Base class for all classes in this file
3060 */
3061 class MakeBase
3062 {
3063 public:
3065 MakeBase()
3066 { line = 0; }
3067 virtual ~MakeBase()
3068 {}
3070 /**
3071 * Return the URI of the file associated with this object
3072 */
3073 URI getURI()
3074 { return uri; }
3076 /**
3077 * Set the uri to the given string
3078 */
3079 void setURI(const String &uristr)
3080 { uri.parse(uristr); }
3082 /**
3083 * Resolve another path relative to this one
3084 */
3085 String resolve(const String &otherPath);
3087 /**
3088 * replace variable refs like ${a} with their values
3089 * Assume that the string has already been syntax validated
3090 */
3091 String eval(const String &s, const String &defaultVal);
3093 /**
3094 * replace variable refs like ${a} with their values
3095 * return true or false
3096 * Assume that the string has already been syntax validated
3097 */
3098 bool evalBool(const String &s, bool defaultVal);
3100 /**
3101 * Get an element attribute, performing substitutions if necessary
3102 */
3103 bool getAttribute(Element *elem, const String &name, String &result);
3105 /**
3106 * Get an element value, performing substitutions if necessary
3107 */
3108 bool getValue(Element *elem, String &result);
3110 /**
3111 * Set the current line number in the file
3112 */
3113 void setLine(int val)
3114 { line = val; }
3116 /**
3117 * Get the current line number in the file
3118 */
3119 int getLine()
3120 { return line; }
3123 /**
3124 * Set a property to a given value
3125 */
3126 virtual void setProperty(const String &name, const String &val)
3127 {
3128 properties[name] = val;
3129 }
3131 /**
3132 * Return a named property is found, else a null string
3133 */
3134 virtual String getProperty(const String &name)
3135 {
3136 String val;
3137 std::map<String, String>::iterator iter = properties.find(name);
3138 if (iter != properties.end())
3139 val = iter->second;
3140 String sval;
3141 if (!getSubstitutions(val, sval))
3142 return false;
3143 return sval;
3144 }
3146 /**
3147 * Return true if a named property is found, else false
3148 */
3149 virtual bool hasProperty(const String &name)
3150 {
3151 std::map<String, String>::iterator iter = properties.find(name);
3152 if (iter == properties.end())
3153 return false;
3154 return true;
3155 }
3158 protected:
3160 /**
3161 * The path to the file associated with this object
3162 */
3163 URI uri;
3165 /**
3166 * If this prefix is seen in a substitution, use an environment
3167 * variable.
3168 * example: <property environment="env"/>
3169 * ${env.JAVA_HOME}
3170 */
3171 String envPrefix;
3173 /**
3174 * If this prefix is seen in a substitution, use as a
3175 * pkg-config 'all' query
3176 * example: <property pkg-config="pc"/>
3177 * ${pc.gtkmm}
3178 */
3179 String pcPrefix;
3181 /**
3182 * If this prefix is seen in a substitution, use as a
3183 * pkg-config 'cflags' query
3184 * example: <property pkg-config="pcc"/>
3185 * ${pcc.gtkmm}
3186 */
3187 String pccPrefix;
3189 /**
3190 * If this prefix is seen in a substitution, use as a
3191 * pkg-config 'libs' query
3192 * example: <property pkg-config-libs="pcl"/>
3193 * ${pcl.gtkmm}
3194 */
3195 String pclPrefix;
3197 /**
3198 * If this prefix is seen in a substitution, use as a
3199 * Subversion "svn info" query
3200 * example: <property subversion="svn"/>
3201 * ${svn.Revision}
3202 */
3203 String svnPrefix;
3209 /**
3210 * Print a printf()-like formatted error message
3211 */
3212 void error(const char *fmt, ...);
3214 /**
3215 * Print a printf()-like formatted trace message
3216 */
3217 void status(const char *fmt, ...);
3219 /**
3220 * Show target status
3221 */
3222 void targetstatus(const char *fmt, ...);
3224 /**
3225 * Print a printf()-like formatted trace message
3226 */
3227 void trace(const char *fmt, ...);
3229 /**
3230 * Check if a given string matches a given regex pattern
3231 */
3232 bool regexMatch(const String &str, const String &pattern);
3234 /**
3235 *
3236 */
3237 String getSuffix(const String &fname);
3239 /**
3240 * Break up a string into substrings delimited the characters
3241 * in delimiters. Null-length substrings are ignored
3242 */
3243 std::vector<String> tokenize(const String &val,
3244 const String &delimiters);
3246 /**
3247 * replace runs of whitespace with a space
3248 */
3249 String strip(const String &s);
3251 /**
3252 * remove leading whitespace from each line
3253 */
3254 String leftJustify(const String &s);
3256 /**
3257 * remove leading and trailing whitespace from string
3258 */
3259 String trim(const String &s);
3261 /**
3262 * Return a lower case version of the given string
3263 */
3264 String toLower(const String &s);
3266 /**
3267 * Return the native format of the canonical
3268 * path which we store
3269 */
3270 String getNativePath(const String &path);
3272 /**
3273 * Execute a shell command. Outbuf is a ref to a string
3274 * to catch the result.
3275 */
3276 bool executeCommand(const String &call,
3277 const String &inbuf,
3278 String &outbuf,
3279 String &errbuf);
3280 /**
3281 * List all directories in a given base and starting directory
3282 * It is usually called like:
3283 * bool ret = listDirectories("src", "", result);
3284 */
3285 bool listDirectories(const String &baseName,
3286 const String &dirname,
3287 std::vector<String> &res);
3289 /**
3290 * Find all files in the named directory
3291 */
3292 bool listFiles(const String &baseName,
3293 const String &dirname,
3294 std::vector<String> &result);
3296 /**
3297 * Perform a listing for a fileset
3298 */
3299 bool listFiles(MakeBase &propRef, FileSet &fileSet);
3301 /**
3302 * Parse a <patternset>
3303 */
3304 bool parsePatternSet(Element *elem,
3305 MakeBase &propRef,
3306 std::vector<String> &includes,
3307 std::vector<String> &excludes);
3309 /**
3310 * Parse a <fileset> entry, and determine which files
3311 * should be included
3312 */
3313 bool parseFileSet(Element *elem,
3314 MakeBase &propRef,
3315 FileSet &fileSet);
3316 /**
3317 * Parse a <filelist> entry
3318 */
3319 bool parseFileList(Element *elem,
3320 MakeBase &propRef,
3321 FileList &fileList);
3323 /**
3324 * Return this object's property list
3325 */
3326 virtual std::map<String, String> &getProperties()
3327 { return properties; }
3330 std::map<String, String> properties;
3332 /**
3333 * Create a directory, making intermediate dirs
3334 * if necessary
3335 */
3336 bool createDirectory(const String &dirname);
3338 /**
3339 * Delete a directory and its children if desired
3340 */
3341 bool removeDirectory(const String &dirName);
3343 /**
3344 * Copy a file from one name to another. Perform only if needed
3345 */
3346 bool copyFile(const String &srcFile, const String &destFile);
3348 /**
3349 * Delete a file
3350 */
3351 bool removeFile(const String &file);
3353 /**
3354 * Tests if the file exists
3355 */
3356 bool fileExists(const String &fileName);
3358 /**
3359 * Tests if the file exists and is a regular file
3360 */
3361 bool isRegularFile(const String &fileName);
3363 /**
3364 * Tests if the file exists and is a directory
3365 */
3366 bool isDirectory(const String &fileName);
3368 /**
3369 * Tests is the modification date of fileA is newer than fileB
3370 */
3371 bool isNewerThan(const String &fileA, const String &fileB);
3373 private:
3375 bool pkgConfigRecursive(const String packageName,
3376 const String &path,
3377 const String &prefix,
3378 int query,
3379 String &result,
3380 std::set<String> &deplist);
3382 /**
3383 * utility method to query for "all", "cflags", or "libs" for this package and its
3384 * dependencies. 0, 1, 2
3385 */
3386 bool pkgConfigQuery(const String &packageName, int query, String &result);
3388 /**
3389 * replace a variable ref like ${a} with a value
3390 */
3391 bool lookupProperty(const String &s, String &result);
3393 /**
3394 * called by getSubstitutions(). This is in case a looked-up string
3395 * has substitutions also.
3396 */
3397 bool getSubstitutionsRecursive(const String &s, String &result, int depth);
3399 /**
3400 * replace variable refs in a string like ${a} with their values
3401 */
3402 bool getSubstitutions(const String &s, String &result);
3404 int line;
3407 };
3411 /**
3412 * Define the pkg-config class here, since it will be used in MakeBase method
3413 * implementations.
3414 */
3415 class PkgConfig : public MakeBase
3416 {
3418 public:
3420 /**
3421 *
3422 */
3423 PkgConfig()
3424 {
3425 path = ".";
3426 prefix = "/target";
3427 init();
3428 }
3430 /**
3431 *
3432 */
3433 PkgConfig(const PkgConfig &other)
3434 { assign(other); }
3436 /**
3437 *
3438 */
3439 PkgConfig &operator=(const PkgConfig &other)
3440 { assign(other); return *this; }
3442 /**
3443 *
3444 */
3445 virtual ~PkgConfig()
3446 { }
3448 /**
3449 *
3450 */
3451 virtual String getName()
3452 { return name; }
3454 /**
3455 *
3456 */
3457 virtual String getPath()
3458 { return path; }
3460 /**
3461 *
3462 */
3463 virtual void setPath(const String &val)
3464 { path = val; }
3466 /**
3467 *
3468 */
3469 virtual String getPrefix()
3470 { return prefix; }
3472 /**
3473 * Allow the user to override the prefix in the file
3474 */
3475 virtual void setPrefix(const String &val)
3476 { prefix = val; }
3478 /**
3479 *
3480 */
3481 virtual String getDescription()
3482 { return description; }
3484 /**
3485 *
3486 */
3487 virtual String getCflags()
3488 { return cflags; }
3490 /**
3491 *
3492 */
3493 virtual String getLibs()
3494 { return libs; }
3496 /**
3497 *
3498 */
3499 virtual String getAll()
3500 {
3501 String ret = cflags;
3502 ret.append(" ");
3503 ret.append(libs);
3504 return ret;
3505 }
3507 /**
3508 *
3509 */
3510 virtual String getVersion()
3511 { return version; }
3513 /**
3514 *
3515 */
3516 virtual int getMajorVersion()
3517 { return majorVersion; }
3519 /**
3520 *
3521 */
3522 virtual int getMinorVersion()
3523 { return minorVersion; }
3525 /**
3526 *
3527 */
3528 virtual int getMicroVersion()
3529 { return microVersion; }
3531 /**
3532 *
3533 */
3534 virtual std::map<String, String> &getAttributes()
3535 { return attrs; }
3537 /**
3538 *
3539 */
3540 virtual std::vector<String> &getRequireList()
3541 { return requireList; }
3543 /**
3544 * Read a file for its details
3545 */
3546 virtual bool readFile(const String &fileName);
3548 /**
3549 * Read a file for its details
3550 */
3551 virtual bool query(const String &name);
3553 private:
3555 void init()
3556 {
3557 //do not set path and prefix here
3558 name = "";
3559 description = "";
3560 cflags = "";
3561 libs = "";
3562 requires = "";
3563 version = "";
3564 majorVersion = 0;
3565 minorVersion = 0;
3566 microVersion = 0;
3567 fileName = "";
3568 attrs.clear();
3569 requireList.clear();
3570 }
3572 void assign(const PkgConfig &other)
3573 {
3574 name = other.name;
3575 path = other.path;
3576 prefix = other.prefix;
3577 description = other.description;
3578 cflags = other.cflags;
3579 libs = other.libs;
3580 requires = other.requires;
3581 version = other.version;
3582 majorVersion = other.majorVersion;
3583 minorVersion = other.minorVersion;
3584 microVersion = other.microVersion;
3585 fileName = other.fileName;
3586 attrs = other.attrs;
3587 requireList = other.requireList;
3588 }
3592 int get(int pos);
3594 int skipwhite(int pos);
3596 int getword(int pos, String &ret);
3598 /**
3599 * Very important
3600 */
3601 bool parseRequires();
3603 void parseVersion();
3605 bool parseLine(const String &lineBuf);
3607 bool parse(const String &buf);
3609 void dumpAttrs();
3611 String name;
3613 String path;
3615 String prefix;
3617 String description;
3619 String cflags;
3621 String libs;
3623 String requires;
3625 String version;
3627 int majorVersion;
3629 int minorVersion;
3631 int microVersion;
3633 String fileName;
3635 std::map<String, String> attrs;
3637 std::vector<String> requireList;
3639 char *parsebuf;
3640 int parselen;
3641 };
3645 /**
3646 * Execute the "svn info" command and parse the result.
3647 * This is a simple, small class. Define here, because it
3648 * is used by MakeBase implementation methods.
3649 */
3650 class SvnInfo : public MakeBase
3651 {
3652 public:
3654 #if 0
3655 /**
3656 * Safe way. Execute "svn info --xml" and parse the result. Search for
3657 * elements/attributes. Safe from changes in format.
3658 */
3659 bool query(const String &name, String &res)
3660 {
3661 String cmd = "svn info --xml";
3663 String outString, errString;
3664 bool ret = executeCommand(cmd.c_str(), "", outString, errString);
3665 if (!ret)
3666 {
3667 error("error executing '%s': %s", cmd.c_str(), errString.c_str());
3668 return false;
3669 }
3670 Parser parser;
3671 Element *elem = parser.parse(outString);
3672 if (!elem)
3673 {
3674 error("error parsing 'svn info' xml result: %s", outString.c_str());
3675 return false;
3676 }
3678 res = elem->getTagValue(name);
3679 if (res.size()==0)
3680 {
3681 res = elem->getTagAttribute("entry", name);
3682 }
3683 return true;
3684 }
3685 #else
3688 /**
3689 * Universal way. Parse the file directly. Not so safe from
3690 * changes in format.
3691 */
3692 bool query(const String &name, String &res)
3693 {
3694 String fileName = resolve(".svn/entries");
3695 String nFileName = getNativePath(fileName);
3697 std::map<String, String> properties;
3699 FILE *f = fopen(nFileName.c_str(), "r");
3700 if (!f)
3701 {
3702 error("could not open SVN 'entries' file");
3703 return false;
3704 }
3706 const char *fieldNames[] =
3707 {
3708 "format-nbr",
3709 "name",
3710 "kind",
3711 "revision",
3712 "url",
3713 "repos",
3714 "schedule",
3715 "text-time",
3716 "checksum",
3717 "committed-date",
3718 "committed-rev",
3719 "last-author",
3720 "has-props",
3721 "has-prop-mods",
3722 "cachable-props",
3723 };
3725 for (int i=0 ; i<15 ; i++)
3726 {
3727 inbuf[0] = '\0';
3728 if (feof(f) || !fgets(inbuf, 255, f))
3729 break;
3730 properties[fieldNames[i]] = trim(inbuf);
3731 }
3732 fclose(f);
3734 res = properties[name];
3736 return true;
3737 }
3739 private:
3741 char inbuf[256];
3743 #endif
3745 };
3752 /**
3753 * Print a printf()-like formatted error message
3754 */
3755 void MakeBase::error(const char *fmt, ...)
3756 {
3757 va_list args;
3758 va_start(args,fmt);
3759 fprintf(stderr, "Make error line %d: ", line);
3760 vfprintf(stderr, fmt, args);
3761 fprintf(stderr, "\n");
3762 va_end(args) ;
3763 }
3767 /**
3768 * Print a printf()-like formatted trace message
3769 */
3770 void MakeBase::status(const char *fmt, ...)
3771 {
3772 va_list args;
3773 //fprintf(stdout, " ");
3774 va_start(args,fmt);
3775 vfprintf(stdout, fmt, args);
3776 va_end(args);
3777 fprintf(stdout, "\n");
3778 fflush(stdout);
3779 }
3782 /**
3783 * Print a printf()-like formatted trace message
3784 */
3785 void MakeBase::trace(const char *fmt, ...)
3786 {
3787 va_list args;
3788 fprintf(stdout, "Make: ");
3789 va_start(args,fmt);
3790 vfprintf(stdout, fmt, args);
3791 va_end(args) ;
3792 fprintf(stdout, "\n");
3793 fflush(stdout);
3794 }
3798 /**
3799 * Resolve another path relative to this one
3800 */
3801 String MakeBase::resolve(const String &otherPath)
3802 {
3803 URI otherURI(otherPath);
3804 URI fullURI = uri.resolve(otherURI);
3805 String ret = fullURI.toString();
3806 return ret;
3807 }
3811 /**
3812 * Check if a given string matches a given regex pattern
3813 */
3814 bool MakeBase::regexMatch(const String &str, const String &pattern)
3815 {
3816 const TRexChar *terror = NULL;
3817 const TRexChar *cpat = pattern.c_str();
3818 TRex *expr = trex_compile(cpat, &terror);
3819 if (!expr)
3820 {
3821 if (!terror)
3822 terror = "undefined";
3823 error("compilation error [%s]!\n", terror);
3824 return false;
3825 }
3827 bool ret = true;
3829 const TRexChar *cstr = str.c_str();
3830 if (trex_match(expr, cstr))
3831 {
3832 ret = true;
3833 }
3834 else
3835 {
3836 ret = false;
3837 }
3839 trex_free(expr);
3841 return ret;
3842 }
3844 /**
3845 * Return the suffix, if any, of a file name
3846 */
3847 String MakeBase::getSuffix(const String &fname)
3848 {
3849 if (fname.size() < 2)
3850 return "";
3851 unsigned int pos = fname.find_last_of('.');
3852 if (pos == fname.npos)
3853 return "";
3854 pos++;
3855 String res = fname.substr(pos, fname.size()-pos);
3856 //trace("suffix:%s", res.c_str());
3857 return res;
3858 }
3862 /**
3863 * Break up a string into substrings delimited the characters
3864 * in delimiters. Null-length substrings are ignored
3865 */
3866 std::vector<String> MakeBase::tokenize(const String &str,
3867 const String &delimiters)
3868 {
3870 std::vector<String> res;
3871 char *del = (char *)delimiters.c_str();
3872 String dmp;
3873 for (unsigned int i=0 ; i<str.size() ; i++)
3874 {
3875 char ch = str[i];
3876 char *p = (char *)0;
3877 for (p=del ; *p ; p++)
3878 if (*p == ch)
3879 break;
3880 if (*p)
3881 {
3882 if (dmp.size() > 0)
3883 {
3884 res.push_back(dmp);
3885 dmp.clear();
3886 }
3887 }
3888 else
3889 {
3890 dmp.push_back(ch);
3891 }
3892 }
3893 //Add tail
3894 if (dmp.size() > 0)
3895 {
3896 res.push_back(dmp);
3897 dmp.clear();
3898 }
3900 return res;
3901 }
3905 /**
3906 * replace runs of whitespace with a single space
3907 */
3908 String MakeBase::strip(const String &s)
3909 {
3910 int len = s.size();
3911 String stripped;
3912 for (int i = 0 ; i<len ; i++)
3913 {
3914 char ch = s[i];
3915 if (isspace(ch))
3916 {
3917 stripped.push_back(' ');
3918 for ( ; i<len ; i++)
3919 {
3920 ch = s[i];
3921 if (!isspace(ch))
3922 {
3923 stripped.push_back(ch);
3924 break;
3925 }
3926 }
3927 }
3928 else
3929 {
3930 stripped.push_back(ch);
3931 }
3932 }
3933 return stripped;
3934 }
3936 /**
3937 * remove leading whitespace from each line
3938 */
3939 String MakeBase::leftJustify(const String &s)
3940 {
3941 String out;
3942 int len = s.size();
3943 for (int i = 0 ; i<len ; )
3944 {
3945 char ch;
3946 //Skip to first visible character
3947 while (i<len)
3948 {
3949 ch = s[i];
3950 if (ch == '\n' || ch == '\r'
3951 || !isspace(ch))
3952 break;
3953 i++;
3954 }
3955 //Copy the rest of the line
3956 while (i<len)
3957 {
3958 ch = s[i];
3959 if (ch == '\n' || ch == '\r')
3960 {
3961 if (ch != '\r')
3962 out.push_back('\n');
3963 i++;
3964 break;
3965 }
3966 else
3967 {
3968 out.push_back(ch);
3969 }
3970 i++;
3971 }
3972 }
3973 return out;
3974 }
3977 /**
3978 * Removes whitespace from beginning and end of a string
3979 */
3980 String MakeBase::trim(const String &s)
3981 {
3982 if (s.size() < 1)
3983 return s;
3985 //Find first non-ws char
3986 unsigned int begin = 0;
3987 for ( ; begin < s.size() ; begin++)
3988 {
3989 if (!isspace(s[begin]))
3990 break;
3991 }
3993 //Find first non-ws char, going in reverse
3994 unsigned int end = s.size() - 1;
3995 for ( ; end > begin ; end--)
3996 {
3997 if (!isspace(s[end]))
3998 break;
3999 }
4000 //trace("begin:%d end:%d", begin, end);
4002 String res = s.substr(begin, end-begin+1);
4003 return res;
4004 }
4007 /**
4008 * Return a lower case version of the given string
4009 */
4010 String MakeBase::toLower(const String &s)
4011 {
4012 if (s.size()==0)
4013 return s;
4015 String ret;
4016 for(unsigned int i=0; i<s.size() ; i++)
4017 {
4018 ret.push_back(tolower(s[i]));
4019 }
4020 return ret;
4021 }
4024 /**
4025 * Return the native format of the canonical
4026 * path which we store
4027 */
4028 String MakeBase::getNativePath(const String &path)
4029 {
4030 #ifdef __WIN32__
4031 String npath;
4032 unsigned int firstChar = 0;
4033 if (path.size() >= 3)
4034 {
4035 if (path[0] == '/' &&
4036 isalpha(path[1]) &&
4037 path[2] == ':')
4038 firstChar++;
4039 }
4040 for (unsigned int i=firstChar ; i<path.size() ; i++)
4041 {
4042 char ch = path[i];
4043 if (ch == '/')
4044 npath.push_back('\\');
4045 else
4046 npath.push_back(ch);
4047 }
4048 return npath;
4049 #else
4050 return path;
4051 #endif
4052 }
4055 #ifdef __WIN32__
4056 #include <tchar.h>
4058 static String win32LastError()
4059 {
4061 DWORD dw = GetLastError();
4063 LPVOID str;
4064 FormatMessage(
4065 FORMAT_MESSAGE_ALLOCATE_BUFFER |
4066 FORMAT_MESSAGE_FROM_SYSTEM,
4067 NULL,
4068 dw,
4069 0,
4070 (LPTSTR) &str,
4071 0, NULL );
4072 LPTSTR p = _tcschr((const char *)str, _T('\r'));
4073 if(p != NULL)
4074 { // lose CRLF
4075 *p = _T('\0');
4076 }
4077 String ret = (char *)str;
4078 LocalFree(str);
4080 return ret;
4081 }
4082 #endif
4087 #ifdef __WIN32__
4089 /**
4090 * Execute a system call, using pipes to send data to the
4091 * program's stdin, and reading stdout and stderr.
4092 */
4093 bool MakeBase::executeCommand(const String &command,
4094 const String &inbuf,
4095 String &outbuf,
4096 String &errbuf)
4097 {
4099 status("============ cmd ============\n%s\n=============================",
4100 command.c_str());
4102 outbuf.clear();
4103 errbuf.clear();
4106 /*
4107 I really hate having win32 code in this program, but the
4108 read buffer in command.com and cmd.exe are just too small
4109 for the large commands we need for compiling and linking.
4110 */
4112 bool ret = true;
4114 //# Allocate a separate buffer for safety
4115 char *paramBuf = new char[command.size() + 1];
4116 if (!paramBuf)
4117 {
4118 error("executeCommand cannot allocate command buffer");
4119 return false;
4120 }
4121 strcpy(paramBuf, (char *)command.c_str());
4123 //# Go to http://msdn2.microsoft.com/en-us/library/ms682499.aspx
4124 //# to see how Win32 pipes work
4126 //# Create pipes
4127 SECURITY_ATTRIBUTES saAttr;
4128 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4129 saAttr.bInheritHandle = TRUE;
4130 saAttr.lpSecurityDescriptor = NULL;
4131 HANDLE stdinRead, stdinWrite;
4132 HANDLE stdoutRead, stdoutWrite;
4133 HANDLE stderrRead, stderrWrite;
4134 if (!CreatePipe(&stdinRead, &stdinWrite, &saAttr, 0))
4135 {
4136 error("executeProgram: could not create pipe");
4137 delete[] paramBuf;
4138 return false;
4139 }
4140 SetHandleInformation(stdinWrite, HANDLE_FLAG_INHERIT, 0);
4141 if (!CreatePipe(&stdoutRead, &stdoutWrite, &saAttr, 0))
4142 {
4143 error("executeProgram: could not create pipe");
4144 delete[] paramBuf;
4145 return false;
4146 }
4147 SetHandleInformation(stdoutRead, HANDLE_FLAG_INHERIT, 0);
4148 if (&outbuf != &errbuf) {
4149 if (!CreatePipe(&stderrRead, &stderrWrite, &saAttr, 0))
4150 {
4151 error("executeProgram: could not create pipe");
4152 delete[] paramBuf;
4153 return false;
4154 }
4155 SetHandleInformation(stderrRead, HANDLE_FLAG_INHERIT, 0);
4156 } else {
4157 stderrRead = stdoutRead;
4158 stderrWrite = stdoutWrite;
4159 }
4161 // Create the process
4162 STARTUPINFO siStartupInfo;
4163 PROCESS_INFORMATION piProcessInfo;
4164 memset(&siStartupInfo, 0, sizeof(siStartupInfo));
4165 memset(&piProcessInfo, 0, sizeof(piProcessInfo));
4166 siStartupInfo.cb = sizeof(siStartupInfo);
4167 siStartupInfo.hStdError = stderrWrite;
4168 siStartupInfo.hStdOutput = stdoutWrite;
4169 siStartupInfo.hStdInput = stdinRead;
4170 siStartupInfo.dwFlags |= STARTF_USESTDHANDLES;
4172 if (!CreateProcess(NULL, paramBuf, NULL, NULL, true,
4173 0, NULL, NULL, &siStartupInfo,
4174 &piProcessInfo))
4175 {
4176 error("executeCommand : could not create process : %s",
4177 win32LastError().c_str());
4178 ret = false;
4179 }
4181 delete[] paramBuf;
4183 DWORD bytesWritten;
4184 if (inbuf.size()>0 &&
4185 !WriteFile(stdinWrite, inbuf.c_str(), inbuf.size(),
4186 &bytesWritten, NULL))
4187 {
4188 error("executeCommand: could not write to pipe");
4189 return false;
4190 }
4191 if (!CloseHandle(stdinWrite))
4192 {
4193 error("executeCommand: could not close write pipe");
4194 return false;
4195 }
4196 if (!CloseHandle(stdoutWrite))
4197 {
4198 error("executeCommand: could not close read pipe");
4199 return false;
4200 }
4201 if (stdoutWrite != stderrWrite && !CloseHandle(stderrWrite))
4202 {
4203 error("executeCommand: could not close read pipe");
4204 return false;
4205 }
4207 bool lastLoop = false;
4208 while (true)
4209 {
4210 DWORD avail;
4211 DWORD bytesRead;
4212 char readBuf[4096];
4214 //trace("## stderr");
4215 PeekNamedPipe(stderrRead, NULL, 0, NULL, &avail, NULL);
4216 if (avail > 0)
4217 {
4218 bytesRead = 0;
4219 if (avail>4096) avail = 4096;
4220 ReadFile(stderrRead, readBuf, avail, &bytesRead, NULL);
4221 if (bytesRead > 0)
4222 {
4223 for (unsigned int i=0 ; i<bytesRead ; i++)
4224 errbuf.push_back(readBuf[i]);
4225 }
4226 }
4228 //trace("## stdout");
4229 PeekNamedPipe(stdoutRead, NULL, 0, NULL, &avail, NULL);
4230 if (avail > 0)
4231 {
4232 bytesRead = 0;
4233 if (avail>4096) avail = 4096;
4234 ReadFile(stdoutRead, readBuf, avail, &bytesRead, NULL);
4235 if (bytesRead > 0)
4236 {
4237 for (unsigned int i=0 ; i<bytesRead ; i++)
4238 outbuf.push_back(readBuf[i]);
4239 }
4240 }
4242 //Was this the final check after program done?
4243 if (lastLoop)
4244 break;
4246 DWORD exitCode;
4247 GetExitCodeProcess(piProcessInfo.hProcess, &exitCode);
4248 if (exitCode != STILL_ACTIVE)
4249 lastLoop = true;
4251 Sleep(10);
4252 }
4253 //trace("outbuf:%s", outbuf.c_str());
4254 if (!CloseHandle(stdoutRead))
4255 {
4256 error("executeCommand: could not close read pipe");
4257 return false;
4258 }
4259 if (stdoutRead != stderrRead && !CloseHandle(stderrRead))
4260 {
4261 error("executeCommand: could not close read pipe");
4262 return false;
4263 }
4265 DWORD exitCode;
4266 GetExitCodeProcess(piProcessInfo.hProcess, &exitCode);
4267 //trace("exit code:%d", exitCode);
4268 if (exitCode != 0)
4269 {
4270 ret = false;
4271 }
4273 CloseHandle(piProcessInfo.hProcess);
4274 CloseHandle(piProcessInfo.hThread);
4276 return ret;
4278 }
4280 #else /*do it unix style*/
4282 #include <sys/wait.h>
4286 /**
4287 * Execute a system call, using pipes to send data to the
4288 * program's stdin, and reading stdout and stderr.
4289 */
4290 bool MakeBase::executeCommand(const String &command,
4291 const String &inbuf,
4292 String &outbuf,
4293 String &errbuf)
4294 {
4296 status("============ cmd ============\n%s\n=============================",
4297 command.c_str());
4299 outbuf.clear();
4300 errbuf.clear();
4303 int outfds[2];
4304 if (pipe(outfds) < 0)
4305 return false;
4306 int errfds[2];
4307 if (pipe(errfds) < 0)
4308 return false;
4309 int pid = fork();
4310 if (pid < 0)
4311 {
4312 close(outfds[0]);
4313 close(outfds[1]);
4314 close(errfds[0]);
4315 close(errfds[1]);
4316 error("launch of command '%s' failed : %s",
4317 command.c_str(), strerror(errno));
4318 return false;
4319 }
4320 else if (pid > 0) // parent
4321 {
4322 close(outfds[1]);
4323 close(errfds[1]);
4324 }
4325 else // == 0, child
4326 {
4327 close(outfds[0]);
4328 dup2(outfds[1], STDOUT_FILENO);
4329 close(outfds[1]);
4330 close(errfds[0]);
4331 dup2(errfds[1], STDERR_FILENO);
4332 close(errfds[1]);
4334 char *args[4];
4335 args[0] = (char *)"sh";
4336 args[1] = (char *)"-c";
4337 args[2] = (char *)command.c_str();
4338 args[3] = NULL;
4339 execv("/bin/sh", args);
4340 exit(EXIT_FAILURE);
4341 }
4343 String outb;
4344 String errb;
4346 int outRead = outfds[0];
4347 int errRead = errfds[0];
4348 int max = outRead;
4349 if (errRead > max)
4350 max = errRead;
4352 bool outOpen = true;
4353 bool errOpen = true;
4355 while (outOpen || errOpen)
4356 {
4357 char ch;
4358 fd_set fdset;
4359 FD_ZERO(&fdset);
4360 if (outOpen)
4361 FD_SET(outRead, &fdset);
4362 if (errOpen)
4363 FD_SET(errRead, &fdset);
4364 int ret = select(max+1, &fdset, NULL, NULL, NULL);
4365 if (ret < 0)
4366 break;
4367 if (FD_ISSET(outRead, &fdset))
4368 {
4369 if (read(outRead, &ch, 1) <= 0)
4370 { outOpen = false; }
4371 else if (ch <= 0)
4372 { /* outOpen = false; */ }
4373 else
4374 { outb.push_back(ch); }
4375 }
4376 if (FD_ISSET(errRead, &fdset))
4377 {
4378 if (read(errRead, &ch, 1) <= 0)
4379 { errOpen = false; }
4380 else if (ch <= 0)
4381 { /* errOpen = false; */ }
4382 else
4383 { errb.push_back(ch); }
4384 }
4385 }
4387 int childReturnValue;
4388 wait(&childReturnValue);
4390 close(outRead);
4391 close(errRead);
4393 outbuf = outb;
4394 errbuf = errb;
4396 if (childReturnValue != 0)
4397 {
4398 error("exec of command '%s' failed : %s",
4399 command.c_str(), strerror(childReturnValue));
4400 return false;
4401 }
4403 return true;
4404 }
4406 #endif
4411 bool MakeBase::listDirectories(const String &baseName,
4412 const String &dirName,
4413 std::vector<String> &res)
4414 {
4415 res.push_back(dirName);
4416 String fullPath = baseName;
4417 if (dirName.size()>0)
4418 {
4419 if (dirName[0]!='/') fullPath.append("/");
4420 fullPath.append(dirName);
4421 }
4422 DIR *dir = opendir(fullPath.c_str());
4423 while (true)
4424 {
4425 struct dirent *de = readdir(dir);
4426 if (!de)
4427 break;
4429 //Get the directory member name
4430 String s = de->d_name;
4431 if (s.size() == 0 || s[0] == '.')
4432 continue;
4433 String childName = dirName;
4434 childName.append("/");
4435 childName.append(s);
4437 String fullChildPath = baseName;
4438 fullChildPath.append("/");
4439 fullChildPath.append(childName);
4440 struct stat finfo;
4441 String childNative = getNativePath(fullChildPath);
4442 if (cachedStat(childNative, &finfo)<0)
4443 {
4444 error("cannot stat file:%s", childNative.c_str());
4445 }
4446 else if (S_ISDIR(finfo.st_mode))
4447 {
4448 //trace("directory: %s", childName.c_str());
4449 if (!listDirectories(baseName, childName, res))
4450 return false;
4451 }
4452 }
4453 closedir(dir);
4455 return true;
4456 }
4459 bool MakeBase::listFiles(const String &baseDir,
4460 const String &dirName,
4461 std::vector<String> &res)
4462 {
4463 String fullDir = baseDir;
4464 if (dirName.size()>0)
4465 {
4466 fullDir.append("/");
4467 fullDir.append(dirName);
4468 }
4469 String dirNative = getNativePath(fullDir);
4471 std::vector<String> subdirs;
4472 DIR *dir = opendir(dirNative.c_str());
4473 if (!dir)
4474 {
4475 error("Could not open directory %s : %s",
4476 dirNative.c_str(), strerror(errno));
4477 return false;
4478 }
4479 while (true)
4480 {
4481 struct dirent *de = readdir(dir);
4482 if (!de)
4483 break;
4485 //Get the directory member name
4486 String s = de->d_name;
4487 if (s.size() == 0 || s[0] == '.')
4488 continue;
4489 String childName;
4490 if (dirName.size()>0)
4491 {
4492 childName.append(dirName);
4493 childName.append("/");
4494 }
4495 childName.append(s);
4496 String fullChild = baseDir;
4497 fullChild.append("/");
4498 fullChild.append(childName);
4500 if (isDirectory(fullChild))
4501 {
4502 //trace("directory: %s", childName.c_str());
4503 if (!listFiles(baseDir, childName, res))
4504 return false;
4505 continue;
4506 }
4507 else if (!isRegularFile(fullChild))
4508 {
4509 error("unknown file:%s", childName.c_str());
4510 return false;
4511 }
4513 //all done!
4514 res.push_back(childName);
4516 }
4517 closedir(dir);
4519 return true;
4520 }
4523 /**
4524 * Several different classes extend MakeBase. By "propRef", we mean
4525 * the one holding the properties. Likely "Make" itself
4526 */
4527 bool MakeBase::listFiles(MakeBase &propRef, FileSet &fileSet)
4528 {
4529 //before doing the list, resolve any property references
4530 //that might have been specified in the directory name, such as ${src}
4531 String fsDir = fileSet.getDirectory();
4532 String dir;
4533 if (!propRef.getSubstitutions(fsDir, dir))
4534 return false;
4535 String baseDir = propRef.resolve(dir);
4536 std::vector<String> fileList;
4537 if (!listFiles(baseDir, "", fileList))
4538 return false;
4540 std::vector<String> includes = fileSet.getIncludes();
4541 std::vector<String> excludes = fileSet.getExcludes();
4543 std::vector<String> incs;
4544 std::vector<String>::iterator iter;
4546 std::sort(fileList.begin(), fileList.end());
4548 //If there are <includes>, then add files to the output
4549 //in the order of the include list
4550 if (includes.size()==0)
4551 incs = fileList;
4552 else
4553 {
4554 for (iter = includes.begin() ; iter != includes.end() ; iter++)
4555 {
4556 String &pattern = *iter;
4557 std::vector<String>::iterator siter;
4558 for (siter = fileList.begin() ; siter != fileList.end() ; siter++)
4559 {
4560 String s = *siter;
4561 if (regexMatch(s, pattern))
4562 {
4563 //trace("INCLUDED:%s", s.c_str());
4564 incs.push_back(s);
4565 }
4566 }
4567 }
4568 }
4570 //Now trim off the <excludes>
4571 std::vector<String> res;
4572 for (iter = incs.begin() ; iter != incs.end() ; iter++)
4573 {
4574 String s = *iter;
4575 bool skipme = false;
4576 std::vector<String>::iterator siter;
4577 for (siter = excludes.begin() ; siter != excludes.end() ; siter++)
4578 {
4579 String &pattern = *siter;
4580 if (regexMatch(s, pattern))
4581 {
4582 //trace("EXCLUDED:%s", s.c_str());
4583 skipme = true;
4584 break;
4585 }
4586 }
4587 if (!skipme)
4588 res.push_back(s);
4589 }
4591 fileSet.setFiles(res);
4593 return true;
4594 }
4597 /**
4598 * 0 == all, 1 = cflags, 2 = libs
4599 */
4600 bool MakeBase::pkgConfigRecursive(const String packageName,
4601 const String &path,
4602 const String &prefix,
4603 int query,
4604 String &result,
4605 std::set<String> &deplist)
4606 {
4607 PkgConfig pkgConfig;
4608 if (path.size() > 0)
4609 pkgConfig.setPath(path);
4610 if (prefix.size() > 0)
4611 pkgConfig.setPrefix(prefix);
4612 if (!pkgConfig.query(packageName))
4613 return false;
4614 if (query == 0)
4615 result = pkgConfig.getAll();
4616 else if (query == 1)
4617 result = pkgConfig.getCflags();
4618 else
4619 result = pkgConfig.getLibs();
4620 deplist.insert(packageName);
4621 std::vector<String> list = pkgConfig.getRequireList();
4622 for (unsigned int i = 0 ; i<list.size() ; i++)
4623 {
4624 String depPkgName = list[i];
4625 if (deplist.find(depPkgName) != deplist.end())
4626 continue;
4627 String val;
4628 if (!pkgConfigRecursive(depPkgName, path, prefix, query, val, deplist))
4629 {
4630 error("Based on 'requires' attribute of package '%s'", packageName.c_str());
4631 return false;
4632 }
4633 result.append(" ");
4634 result.append(val);
4635 }
4637 return true;
4638 }
4640 bool MakeBase::pkgConfigQuery(const String &packageName, int query, String &result)
4641 {
4642 std::set<String> deplist;
4643 String path = getProperty("pkg-config-path");
4644 if (path.size()>0)
4645 path = resolve(path);
4646 String prefix = getProperty("pkg-config-prefix");
4647 String val;
4648 if (!pkgConfigRecursive(packageName, path, prefix, query, val, deplist))
4649 return false;
4650 result = val;
4651 return true;
4652 }
4656 /**
4657 * replace a variable ref like ${a} with a value
4658 */
4659 bool MakeBase::lookupProperty(const String &propertyName, String &result)
4660 {
4661 String varname = propertyName;
4662 if (envPrefix.size() > 0 &&
4663 varname.compare(0, envPrefix.size(), envPrefix) == 0)
4664 {
4665 varname = varname.substr(envPrefix.size());
4666 char *envstr = getenv(varname.c_str());
4667 if (!envstr)
4668 {
4669 error("environment variable '%s' not defined", varname.c_str());
4670 return false;
4671 }
4672 result = envstr;
4673 }
4674 else if (pcPrefix.size() > 0 &&
4675 varname.compare(0, pcPrefix.size(), pcPrefix) == 0)
4676 {
4677 varname = varname.substr(pcPrefix.size());
4678 String val;
4679 if (!pkgConfigQuery(varname, 0, val))
4680 return false;
4681 result = val;
4682 }
4683 else if (pccPrefix.size() > 0 &&
4684 varname.compare(0, pccPrefix.size(), pccPrefix) == 0)
4685 {
4686 varname = varname.substr(pccPrefix.size());
4687 String val;
4688 if (!pkgConfigQuery(varname, 1, val))
4689 return false;
4690 result = val;
4691 }
4692 else if (pclPrefix.size() > 0 &&
4693 varname.compare(0, pclPrefix.size(), pclPrefix) == 0)
4694 {
4695 varname = varname.substr(pclPrefix.size());
4696 String val;
4697 if (!pkgConfigQuery(varname, 2, val))
4698 return false;
4699 result = val;
4700 }
4701 else if (svnPrefix.size() > 0 &&
4702 varname.compare(0, svnPrefix.size(), svnPrefix) == 0)
4703 {
4704 varname = varname.substr(svnPrefix.size());
4705 String val;
4706 SvnInfo svnInfo;
4707 if (varname == "revision")
4708 {
4709 if (!svnInfo.query(varname, val))
4710 return "";
4711 result = "r"+val;
4712 }
4713 if (!svnInfo.query(varname, val))
4714 return false;
4715 result = val;
4716 }
4717 else
4718 {
4719 std::map<String, String>::iterator iter;
4720 iter = properties.find(varname);
4721 if (iter != properties.end())
4722 {
4723 result = iter->second;
4724 }
4725 else
4726 {
4727 error("property '%s' not found", varname.c_str());
4728 return false;
4729 }
4730 }
4731 return true;
4732 }
4737 /**
4738 * Analyse a string, looking for any substitutions or other
4739 * things that need resolution
4740 */
4741 bool MakeBase::getSubstitutionsRecursive(const String &str,
4742 String &result, int depth)
4743 {
4744 if (depth > 10)
4745 {
4746 error("nesting of substitutions too deep (>10) for '%s'",
4747 str.c_str());
4748 return false;
4749 }
4750 String s = trim(str);
4751 int len = (int)s.size();
4752 String val;
4753 for (int i=0 ; i<len ; i++)
4754 {
4755 char ch = s[i];
4756 if (ch == '$' && s[i+1] == '{')
4757 {
4758 String varname;
4759 int j = i+2;
4760 for ( ; j<len ; j++)
4761 {
4762 ch = s[j];
4763 if (ch == '$' && s[j+1] == '{')
4764 {
4765 error("attribute %s cannot have nested variable references",
4766 s.c_str());
4767 return false;
4768 }
4769 else if (ch == '}')
4770 {
4771 varname = trim(varname);
4772 String varval;
4773 if (!lookupProperty(varname, varval))
4774 return false;
4775 String varval2;
4776 //Now see if the answer has ${} in it, too
4777 if (!getSubstitutionsRecursive(varval, varval2, depth + 1))
4778 return false;
4779 val.append(varval2);
4780 break;
4781 }
4782 else
4783 {
4784 varname.push_back(ch);
4785 }
4786 }
4787 i = j;
4788 }
4789 else
4790 {
4791 val.push_back(ch);
4792 }
4793 }
4794 result = val;
4795 return true;
4796 }
4798 /**
4799 * Analyse a string, looking for any substitutions or other
4800 * things that need resilution
4801 */
4802 bool MakeBase::getSubstitutions(const String &str, String &result)
4803 {
4804 return getSubstitutionsRecursive(str, result, 0);
4805 }
4809 /**
4810 * replace variable refs like ${a} with their values
4811 * Assume that the string has already been syntax validated
4812 */
4813 String MakeBase::eval(const String &s, const String &defaultVal)
4814 {
4815 if (s.size()==0)
4816 return defaultVal;
4817 String ret;
4818 if (getSubstitutions(s, ret))
4819 return ret;
4820 else
4821 return defaultVal;
4822 }
4825 /**
4826 * replace variable refs like ${a} with their values
4827 * return true or false
4828 * Assume that the string has already been syntax validated
4829 */
4830 bool MakeBase::evalBool(const String &s, bool defaultVal)
4831 {
4832 if (s.size()==0)
4833 return defaultVal;
4834 String val = eval(s, "false");
4835 if (val.size()==0)
4836 return defaultVal;
4837 if (val == "true" || val == "TRUE")
4838 return true;
4839 else
4840 return false;
4841 }
4844 /**
4845 * Get a string attribute, testing it for proper syntax and
4846 * property names.
4847 */
4848 bool MakeBase::getAttribute(Element *elem, const String &name,
4849 String &result)
4850 {
4851 String s = elem->getAttribute(name);
4852 String tmp;
4853 bool ret = getSubstitutions(s, tmp);
4854 if (ret)
4855 result = s; //assign -if- ok
4856 return ret;
4857 }
4860 /**
4861 * Get a string value, testing it for proper syntax and
4862 * property names.
4863 */
4864 bool MakeBase::getValue(Element *elem, String &result)
4865 {
4866 String s = elem->getValue();
4867 String tmp;
4868 bool ret = getSubstitutions(s, tmp);
4869 if (ret)
4870 result = s; //assign -if- ok
4871 return ret;
4872 }
4877 /**
4878 * Parse a <patternset> entry
4879 */
4880 bool MakeBase::parsePatternSet(Element *elem,
4881 MakeBase &propRef,
4882 std::vector<String> &includes,
4883 std::vector<String> &excludes
4884 )
4885 {
4886 std::vector<Element *> children = elem->getChildren();
4887 for (unsigned int i=0 ; i<children.size() ; i++)
4888 {
4889 Element *child = children[i];
4890 String tagName = child->getName();
4891 if (tagName == "exclude")
4892 {
4893 String fname;
4894 if (!propRef.getAttribute(child, "name", fname))
4895 return false;
4896 //trace("EXCLUDE: %s", fname.c_str());
4897 excludes.push_back(fname);
4898 }
4899 else if (tagName == "include")
4900 {
4901 String fname;
4902 if (!propRef.getAttribute(child, "name", fname))
4903 return false;
4904 //trace("INCLUDE: %s", fname.c_str());
4905 includes.push_back(fname);
4906 }
4907 }
4909 return true;
4910 }
4915 /**
4916 * Parse a <fileset> entry, and determine which files
4917 * should be included
4918 */
4919 bool MakeBase::parseFileSet(Element *elem,
4920 MakeBase &propRef,
4921 FileSet &fileSet)
4922 {
4923 String name = elem->getName();
4924 if (name != "fileset")
4925 {
4926 error("expected <fileset>");
4927 return false;
4928 }
4931 std::vector<String> includes;
4932 std::vector<String> excludes;
4934 //A fileset has one implied patternset
4935 if (!parsePatternSet(elem, propRef, includes, excludes))
4936 {
4937 return false;
4938 }
4939 //Look for child tags, including more patternsets
4940 std::vector<Element *> children = elem->getChildren();
4941 for (unsigned int i=0 ; i<children.size() ; i++)
4942 {
4943 Element *child = children[i];
4944 String tagName = child->getName();
4945 if (tagName == "patternset")
4946 {
4947 if (!parsePatternSet(child, propRef, includes, excludes))
4948 {
4949 return false;
4950 }
4951 }
4952 }
4954 String dir;
4955 //Now do the stuff
4956 //Get the base directory for reading file names
4957 if (!propRef.getAttribute(elem, "dir", dir))
4958 return false;
4960 fileSet.setDirectory(dir);
4961 fileSet.setIncludes(includes);
4962 fileSet.setExcludes(excludes);
4964 /*
4965 std::vector<String> fileList;
4966 if (dir.size() > 0)
4967 {
4968 String baseDir = propRef.resolve(dir);
4969 if (!listFiles(baseDir, "", includes, excludes, fileList))
4970 return false;
4971 }
4972 std::sort(fileList.begin(), fileList.end());
4973 result = fileList;
4974 */
4977 /*
4978 for (unsigned int i=0 ; i<result.size() ; i++)
4979 {
4980 trace("RES:%s", result[i].c_str());
4981 }
4982 */
4985 return true;
4986 }
4988 /**
4989 * Parse a <filelist> entry. This is far simpler than FileSet,
4990 * since no directory scanning is needed. The file names are listed
4991 * explicitly.
4992 */
4993 bool MakeBase::parseFileList(Element *elem,
4994 MakeBase &propRef,
4995 FileList &fileList)
4996 {
4997 std::vector<String> fnames;
4998 //Look for child tags, namely "file"
4999 std::vector<Element *> children = elem->getChildren();
5000 for (unsigned int i=0 ; i<children.size() ; i++)
5001 {
5002 Element *child = children[i];
5003 String tagName = child->getName();
5004 if (tagName == "file")
5005 {
5006 String fname = child->getAttribute("name");
5007 if (fname.size()==0)
5008 {
5009 error("<file> element requires name="" attribute");
5010 return false;
5011 }
5012 fnames.push_back(fname);
5013 }
5014 else
5015 {
5016 error("tag <%s> not allowed in <fileset>", tagName.c_str());
5017 return false;
5018 }
5019 }
5021 String dir;
5022 //Get the base directory for reading file names
5023 if (!propRef.getAttribute(elem, "dir", dir))
5024 return false;
5025 fileList.setDirectory(dir);
5026 fileList.setFiles(fnames);
5028 return true;
5029 }
5033 /**
5034 * Create a directory, making intermediate dirs
5035 * if necessary
5036 */
5037 bool MakeBase::createDirectory(const String &dirname)
5038 {
5039 //trace("## createDirectory: %s", dirname.c_str());
5040 //## first check if it exists
5041 struct stat finfo;
5042 String nativeDir = getNativePath(dirname);
5043 char *cnative = (char *) nativeDir.c_str();
5044 #ifdef __WIN32__
5045 if (strlen(cnative)==2 && cnative[1]==':')
5046 return true;
5047 #endif
5048 if (cachedStat(nativeDir, &finfo)==0)
5049 {
5050 if (!S_ISDIR(finfo.st_mode))
5051 {
5052 error("mkdir: file %s exists but is not a directory",
5053 cnative);
5054 return false;
5055 }
5056 else //exists
5057 {
5058 return true;
5059 }
5060 }
5062 //## 2: pull off the last path segment, if any,
5063 //## to make the dir 'above' this one, if necessary
5064 unsigned int pos = dirname.find_last_of('/');
5065 if (pos>0 && pos != dirname.npos)
5066 {
5067 String subpath = dirname.substr(0, pos);
5068 //A letter root (c:) ?
5069 if (!createDirectory(subpath))
5070 return false;
5071 }
5073 //## 3: now make
5074 #ifdef __WIN32__
5075 if (mkdir(cnative)<0)
5076 #else
5077 if (mkdir(cnative, S_IRWXU | S_IRWXG | S_IRWXO)<0)
5078 #endif
5079 {
5080 error("cannot make directory '%s' : %s",
5081 cnative, strerror(errno));
5082 return false;
5083 }
5085 removeFromStatCache(nativeDir);
5087 return true;
5088 }
5091 /**
5092 * Remove a directory recursively
5093 */
5094 bool MakeBase::removeDirectory(const String &dirName)
5095 {
5096 char *dname = (char *)dirName.c_str();
5098 DIR *dir = opendir(dname);
5099 if (!dir)
5100 {
5101 //# Let this fail nicely.
5102 return true;
5103 //error("error opening directory %s : %s", dname, strerror(errno));
5104 //return false;
5105 }
5107 while (true)
5108 {
5109 struct dirent *de = readdir(dir);
5110 if (!de)
5111 break;
5113 //Get the directory member name
5114 String s = de->d_name;
5115 if (s.size() == 0 || s[0] == '.')
5116 continue;
5117 String childName;
5118 if (dirName.size() > 0)
5119 {
5120 childName.append(dirName);
5121 childName.append("/");
5122 }
5123 childName.append(s);
5126 struct stat finfo;
5127 String childNative = getNativePath(childName);
5128 char *cnative = (char *)childNative.c_str();
5129 if (cachedStat(childNative, &finfo)<0)
5130 {
5131 error("cannot stat file:%s", cnative);
5132 }
5133 else if (S_ISDIR(finfo.st_mode))
5134 {
5135 //trace("DEL dir: %s", childName.c_str());
5136 if (!removeDirectory(childName))
5137 {
5138 return false;
5139 }
5140 }
5141 else if (!S_ISREG(finfo.st_mode))
5142 {
5143 //trace("not regular: %s", cnative);
5144 }
5145 else
5146 {
5147 //trace("DEL file: %s", childName.c_str());
5148 if (!removeFile(childName))
5149 {
5150 return false;
5151 }
5152 }
5153 }
5154 closedir(dir);
5156 //Now delete the directory
5157 String native = getNativePath(dirName);
5158 if (rmdir(native.c_str())<0)
5159 {
5160 error("could not delete directory %s : %s",
5161 native.c_str() , strerror(errno));
5162 return false;
5163 }
5165 removeFromStatCache(native);
5167 return true;
5169 }
5172 /**
5173 * Copy a file from one name to another. Perform only if needed
5174 */
5175 bool MakeBase::copyFile(const String &srcFile, const String &destFile)
5176 {
5177 //# 1 Check up-to-date times
5178 String srcNative = getNativePath(srcFile);
5179 struct stat srcinfo;
5180 if (cachedStat(srcNative, &srcinfo)<0)
5181 {
5182 error("source file %s for copy does not exist",
5183 srcNative.c_str());
5184 return false;
5185 }
5187 String destNative = getNativePath(destFile);
5188 struct stat destinfo;
5189 if (cachedStat(destNative, &destinfo)==0)
5190 {
5191 if (destinfo.st_mtime >= srcinfo.st_mtime)
5192 return true;
5193 }
5195 //# 2 prepare a destination directory if necessary
5196 unsigned int pos = destFile.find_last_of('/');
5197 if (pos != destFile.npos)
5198 {
5199 String subpath = destFile.substr(0, pos);
5200 if (!createDirectory(subpath))
5201 return false;
5202 }
5204 //# 3 do the data copy
5205 #ifndef __WIN32__
5207 FILE *srcf = fopen(srcNative.c_str(), "rb");
5208 if (!srcf)
5209 {
5210 error("copyFile cannot open '%s' for reading", srcNative.c_str());
5211 return false;
5212 }
5213 FILE *destf = fopen(destNative.c_str(), "wb");
5214 if (!destf)
5215 {
5216 error("copyFile cannot open %s for writing", srcNative.c_str());
5217 return false;
5218 }
5220 while (!feof(srcf))
5221 {
5222 int ch = fgetc(srcf);
5223 if (ch<0)
5224 break;
5225 fputc(ch, destf);
5226 }
5228 fclose(destf);
5229 fclose(srcf);
5231 #else
5233 if (!CopyFile(srcNative.c_str(), destNative.c_str(), false))
5234 {
5235 error("copyFile from %s to %s failed",
5236 srcNative.c_str(), destNative.c_str());
5237 return false;
5238 }
5240 #endif /* __WIN32__ */
5242 removeFromStatCache(destNative);
5244 return true;
5245 }
5248 /**
5249 * Delete a file
5250 */
5251 bool MakeBase::removeFile(const String &file)
5252 {
5253 String native = getNativePath(file);
5255 if (!fileExists(native))
5256 {
5257 return true;
5258 }
5260 #ifdef WIN32
5261 // On Windows 'remove' will only delete files
5263 if (remove(native.c_str())<0)
5264 {
5265 if (errno==EACCES)
5266 {
5267 error("File %s is read-only", native.c_str());
5268 }
5269 else if (errno==ENOENT)
5270 {
5271 error("File %s does not exist or is a directory", native.c_str());
5272 }
5273 else
5274 {
5275 error("Failed to delete file %s: %s", native.c_str(), strerror(errno));
5276 }
5277 return false;
5278 }
5280 #else
5282 if (!isRegularFile(native))
5283 {
5284 error("File %s does not exist or is not a regular file", native.c_str());
5285 return false;
5286 }
5288 if (remove(native.c_str())<0)
5289 {
5290 if (errno==EACCES)
5291 {
5292 error("File %s is read-only", native.c_str());
5293 }
5294 else
5295 {
5296 error(
5297 errno==EACCES ? "File %s is read-only" :
5298 errno==ENOENT ? "File %s does not exist or is a directory" :
5299 "Failed to delete file %s: %s", native.c_str());
5300 }
5301 return false;
5302 }
5304 #endif
5306 removeFromStatCache(native);
5308 return true;
5309 }
5312 /**
5313 * Tests if the file exists
5314 */
5315 bool MakeBase::fileExists(const String &fileName)
5316 {
5317 String native = getNativePath(fileName);
5318 struct stat finfo;
5320 //Exists?
5321 if (cachedStat(native, &finfo)<0)
5322 return false;
5324 return true;
5325 }
5328 /**
5329 * Tests if the file exists and is a regular file
5330 */
5331 bool MakeBase::isRegularFile(const String &fileName)
5332 {
5333 String native = getNativePath(fileName);
5334 struct stat finfo;
5336 //Exists?
5337 if (cachedStat(native, &finfo)<0)
5338 return false;
5341 //check the file mode
5342 if (!S_ISREG(finfo.st_mode))
5343 return false;
5345 return true;
5346 }
5348 /**
5349 * Tests if the file exists and is a directory
5350 */
5351 bool MakeBase::isDirectory(const String &fileName)
5352 {
5353 String native = getNativePath(fileName);
5354 struct stat finfo;
5356 //Exists?
5357 if (cachedStat(native, &finfo)<0)
5358 return false;
5361 //check the file mode
5362 if (!S_ISDIR(finfo.st_mode))
5363 return false;
5365 return true;
5366 }
5370 /**
5371 * Tests is the modification of fileA is newer than fileB
5372 */
5373 bool MakeBase::isNewerThan(const String &fileA, const String &fileB)
5374 {
5375 //trace("isNewerThan:'%s' , '%s'", fileA.c_str(), fileB.c_str());
5376 String nativeA = getNativePath(fileA);
5377 struct stat infoA;
5378 //IF source does not exist, NOT newer
5379 if (cachedStat(nativeA, &infoA)<0)
5380 {
5381 return false;
5382 }
5384 String nativeB = getNativePath(fileB);
5385 struct stat infoB;
5386 //IF dest does not exist, YES, newer
5387 if (cachedStat(nativeB, &infoB)<0)
5388 {
5389 return true;
5390 }
5392 //check the actual times
5393 if (infoA.st_mtime > infoB.st_mtime)
5394 {
5395 return true;
5396 }
5398 return false;
5399 }
5402 //########################################################################
5403 //# P K G C O N F I G
5404 //########################################################################
5407 /**
5408 * Get a character from the buffer at pos. If out of range,
5409 * return -1 for safety
5410 */
5411 int PkgConfig::get(int pos)
5412 {
5413 if (pos>parselen)
5414 return -1;
5415 return parsebuf[pos];
5416 }
5420 /**
5421 * Skip over all whitespace characters beginning at pos. Return
5422 * the position of the first non-whitespace character.
5423 * Pkg-config is line-oriented, so check for newline
5424 */
5425 int PkgConfig::skipwhite(int pos)
5426 {
5427 while (pos < parselen)
5428 {
5429 int ch = get(pos);
5430 if (ch < 0)
5431 break;
5432 if (!isspace(ch))
5433 break;
5434 pos++;
5435 }
5436 return pos;
5437 }
5440 /**
5441 * Parse the buffer beginning at pos, for a word. Fill
5442 * 'ret' with the result. Return the position after the
5443 * word.
5444 */
5445 int PkgConfig::getword(int pos, String &ret)
5446 {
5447 while (pos < parselen)
5448 {
5449 int ch = get(pos);
5450 if (ch < 0)
5451 break;
5452 if (!isalnum(ch) && ch != '_' && ch != '-' && ch != '+' && ch != '.')
5453 break;
5454 ret.push_back((char)ch);
5455 pos++;
5456 }
5457 return pos;
5458 }
5460 bool PkgConfig::parseRequires()
5461 {
5462 if (requires.size() == 0)
5463 return true;
5464 parsebuf = (char *)requires.c_str();
5465 parselen = requires.size();
5466 int pos = 0;
5467 while (pos < parselen)
5468 {
5469 pos = skipwhite(pos);
5470 String val;
5471 int pos2 = getword(pos, val);
5472 if (pos2 == pos)
5473 break;
5474 pos = pos2;
5475 //trace("val %s", val.c_str());
5476 requireList.push_back(val);
5477 }
5478 return true;
5479 }
5482 static int getint(const String str)
5483 {
5484 char *s = (char *)str.c_str();
5485 char *ends = NULL;
5486 long val = strtol(s, &ends, 10);
5487 if (ends == s)
5488 return 0L;
5489 else
5490 return val;
5491 }
5493 void PkgConfig::parseVersion()
5494 {
5495 if (version.size() == 0)
5496 return;
5497 String s1, s2, s3;
5498 unsigned int pos = 0;
5499 unsigned int pos2 = version.find('.', pos);
5500 if (pos2 == version.npos)
5501 {
5502 s1 = version;
5503 }
5504 else
5505 {
5506 s1 = version.substr(pos, pos2-pos);
5507 pos = pos2;
5508 pos++;
5509 if (pos < version.size())
5510 {
5511 pos2 = version.find('.', pos);
5512 if (pos2 == version.npos)
5513 {
5514 s2 = version.substr(pos, version.size()-pos);
5515 }
5516 else
5517 {
5518 s2 = version.substr(pos, pos2-pos);
5519 pos = pos2;
5520 pos++;
5521 if (pos < version.size())
5522 s3 = version.substr(pos, pos2-pos);
5523 }
5524 }
5525 }
5527 majorVersion = getint(s1);
5528 minorVersion = getint(s2);
5529 microVersion = getint(s3);
5530 //trace("version:%d.%d.%d", majorVersion,
5531 // minorVersion, microVersion );
5532 }
5535 bool PkgConfig::parseLine(const String &lineBuf)
5536 {
5537 parsebuf = (char *)lineBuf.c_str();
5538 parselen = lineBuf.size();
5539 int pos = 0;
5541 while (pos < parselen)
5542 {
5543 String attrName;
5544 pos = skipwhite(pos);
5545 int ch = get(pos);
5546 if (ch == '#')
5547 {
5548 //comment. eat the rest of the line
5549 while (pos < parselen)
5550 {
5551 ch = get(pos);
5552 if (ch == '\n' || ch < 0)
5553 break;
5554 pos++;
5555 }
5556 continue;
5557 }
5558 pos = getword(pos, attrName);
5559 if (attrName.size() == 0)
5560 continue;
5562 pos = skipwhite(pos);
5563 ch = get(pos);
5564 if (ch != ':' && ch != '=')
5565 {
5566 error("expected ':' or '='");
5567 return false;
5568 }
5569 pos++;
5570 pos = skipwhite(pos);
5571 String attrVal;
5572 while (pos < parselen)
5573 {
5574 ch = get(pos);
5575 if (ch == '\n' || ch < 0)
5576 break;
5577 else if (ch == '$' && get(pos+1) == '{')
5578 {
5579 //# this is a ${substitution}
5580 pos += 2;
5581 String subName;
5582 while (pos < parselen)
5583 {
5584 ch = get(pos);
5585 if (ch < 0)
5586 {
5587 error("unterminated substitution");
5588 return false;
5589 }
5590 else if (ch == '}')
5591 break;
5592 else
5593 subName.push_back((char)ch);
5594 pos++;
5595 }
5596 //trace("subName:%s %s", subName.c_str(), prefix.c_str());
5597 if (subName == "prefix" && prefix.size()>0)
5598 {
5599 attrVal.append(prefix);
5600 //trace("prefix override:%s", prefix.c_str());
5601 }
5602 else
5603 {
5604 String subVal = attrs[subName];
5605 //trace("subVal:%s", subVal.c_str());
5606 attrVal.append(subVal);
5607 }
5608 }
5609 else
5610 attrVal.push_back((char)ch);
5611 pos++;
5612 }
5614 attrVal = trim(attrVal);
5615 attrs[attrName] = attrVal;
5617 String attrNameL = toLower(attrName);
5619 if (attrNameL == "name")
5620 name = attrVal;
5621 else if (attrNameL == "description")
5622 description = attrVal;
5623 else if (attrNameL == "cflags")
5624 cflags = attrVal;
5625 else if (attrNameL == "libs")
5626 libs = attrVal;
5627 else if (attrNameL == "requires")
5628 requires = attrVal;
5629 else if (attrNameL == "version")
5630 version = attrVal;
5632 //trace("name:'%s' value:'%s'",
5633 // attrName.c_str(), attrVal.c_str());
5634 }
5636 return true;
5637 }
5640 bool PkgConfig::parse(const String &buf)
5641 {
5642 init();
5644 String line;
5645 int lineNr = 0;
5646 for (unsigned int p=0 ; p<buf.size() ; p++)
5647 {
5648 int ch = buf[p];
5649 if (ch == '\n' || ch == '\r')
5650 {
5651 if (!parseLine(line))
5652 return false;
5653 line.clear();
5654 lineNr++;
5655 }
5656 else
5657 {
5658 line.push_back(ch);
5659 }
5660 }
5661 if (line.size()>0)
5662 {
5663 if (!parseLine(line))
5664 return false;
5665 }
5667 parseRequires();
5668 parseVersion();
5670 return true;
5671 }
5676 void PkgConfig::dumpAttrs()
5677 {
5678 //trace("### PkgConfig attributes for %s", fileName.c_str());
5679 std::map<String, String>::iterator iter;
5680 for (iter=attrs.begin() ; iter!=attrs.end() ; iter++)
5681 {
5682 trace(" %s = %s", iter->first.c_str(), iter->second.c_str());
5683 }
5684 }
5687 bool PkgConfig::readFile(const String &fname)
5688 {
5689 fileName = getNativePath(fname);
5691 FILE *f = fopen(fileName.c_str(), "r");
5692 if (!f)
5693 {
5694 error("cannot open file '%s' for reading", fileName.c_str());
5695 return false;
5696 }
5697 String buf;
5698 while (true)
5699 {
5700 int ch = fgetc(f);
5701 if (ch < 0)
5702 break;
5703 buf.push_back((char)ch);
5704 }
5705 fclose(f);
5707 //trace("####### File:\n%s", buf.c_str());
5708 if (!parse(buf))
5709 {
5710 return false;
5711 }
5713 //dumpAttrs();
5715 return true;
5716 }
5720 bool PkgConfig::query(const String &pkgName)
5721 {
5722 name = pkgName;
5724 String fname = path;
5725 fname.append("/");
5726 fname.append(name);
5727 fname.append(".pc");
5729 if (!readFile(fname))
5730 {
5731 error("Cannot find package '%s'. Do you have it installed?",
5732 pkgName.c_str());
5733 return false;
5734 }
5736 return true;
5737 }
5740 //########################################################################
5741 //# D E P T O O L
5742 //########################################################################
5746 /**
5747 * Class which holds information for each file.
5748 */
5749 class FileRec
5750 {
5751 public:
5753 typedef enum
5754 {
5755 UNKNOWN,
5756 CFILE,
5757 HFILE,
5758 OFILE
5759 } FileType;
5761 /**
5762 * Constructor
5763 */
5764 FileRec()
5765 { init(); type = UNKNOWN; }
5767 /**
5768 * Copy constructor
5769 */
5770 FileRec(const FileRec &other)
5771 { init(); assign(other); }
5772 /**
5773 * Constructor
5774 */
5775 FileRec(int typeVal)
5776 { init(); type = typeVal; }
5777 /**
5778 * Assignment operator
5779 */
5780 FileRec &operator=(const FileRec &other)
5781 { init(); assign(other); return *this; }
5784 /**
5785 * Destructor
5786 */
5787 ~FileRec()
5788 {}
5790 /**
5791 * Directory part of the file name
5792 */
5793 String path;
5795 /**
5796 * Base name, sans directory and suffix
5797 */
5798 String baseName;
5800 /**
5801 * File extension, such as cpp or h
5802 */
5803 String suffix;
5805 /**
5806 * Type of file: CFILE, HFILE, OFILE
5807 */
5808 int type;
5810 /**
5811 * Used to list files ref'd by this one
5812 */
5813 std::map<String, FileRec *> files;
5816 private:
5818 void init()
5819 {
5820 }
5822 void assign(const FileRec &other)
5823 {
5824 type = other.type;
5825 baseName = other.baseName;
5826 suffix = other.suffix;
5827 files = other.files;
5828 }
5830 };
5834 /**
5835 * Simpler dependency record
5836 */
5837 class DepRec
5838 {
5839 public:
5841 /**
5842 * Constructor
5843 */
5844 DepRec()
5845 {init();}
5847 /**
5848 * Copy constructor
5849 */
5850 DepRec(const DepRec &other)
5851 {init(); assign(other);}
5852 /**
5853 * Constructor
5854 */
5855 DepRec(const String &fname)
5856 {init(); name = fname; }
5857 /**
5858 * Assignment operator
5859 */
5860 DepRec &operator=(const DepRec &other)
5861 {init(); assign(other); return *this;}
5864 /**
5865 * Destructor
5866 */
5867 ~DepRec()
5868 {}
5870 /**
5871 * Directory part of the file name
5872 */
5873 String path;
5875 /**
5876 * Base name, without the path and suffix
5877 */
5878 String name;
5880 /**
5881 * Suffix of the source
5882 */
5883 String suffix;
5886 /**
5887 * Used to list files ref'd by this one
5888 */
5889 std::vector<String> files;
5892 private:
5894 void init()
5895 {
5896 }
5898 void assign(const DepRec &other)
5899 {
5900 path = other.path;
5901 name = other.name;
5902 suffix = other.suffix;
5903 files = other.files; //avoid recursion
5904 }
5906 };
5909 class DepTool : public MakeBase
5910 {
5911 public:
5913 /**
5914 * Constructor
5915 */
5916 DepTool()
5917 { init(); }
5919 /**
5920 * Copy constructor
5921 */
5922 DepTool(const DepTool &other)
5923 { init(); assign(other); }
5925 /**
5926 * Assignment operator
5927 */
5928 DepTool &operator=(const DepTool &other)
5929 { init(); assign(other); return *this; }
5932 /**
5933 * Destructor
5934 */
5935 ~DepTool()
5936 {}
5939 /**
5940 * Reset this section of code
5941 */
5942 virtual void init();
5944 /**
5945 * Reset this section of code
5946 */
5947 virtual void assign(const DepTool &other)
5948 {
5949 }
5951 /**
5952 * Sets the source directory which will be scanned
5953 */
5954 virtual void setSourceDirectory(const String &val)
5955 { sourceDir = val; }
5957 /**
5958 * Returns the source directory which will be scanned
5959 */
5960 virtual String getSourceDirectory()
5961 { return sourceDir; }
5963 /**
5964 * Sets the list of files within the directory to analyze
5965 */
5966 virtual void setFileList(const std::vector<String> &list)
5967 { fileList = list; }
5969 /**
5970 * Creates the list of all file names which will be
5971 * candidates for further processing. Reads make.exclude
5972 * to see which files for directories to leave out.
5973 */
5974 virtual bool createFileList();
5977 /**
5978 * Generates the forward dependency list
5979 */
5980 virtual bool generateDependencies();
5983 /**
5984 * Generates the forward dependency list, saving the file
5985 */
5986 virtual bool generateDependencies(const String &);
5989 /**
5990 * Load a dependency file
5991 */
5992 std::vector<DepRec> loadDepFile(const String &fileName);
5994 /**
5995 * Load a dependency file, generating one if necessary
5996 */
5997 std::vector<DepRec> getDepFile(const String &fileName,
5998 bool forceRefresh);
6000 /**
6001 * Save a dependency file
6002 */
6003 bool saveDepFile(const String &fileName);
6006 private:
6009 /**
6010 *
6011 */
6012 void parseName(const String &fullname,
6013 String &path,
6014 String &basename,
6015 String &suffix);
6017 /**
6018 *
6019 */
6020 int get(int pos);
6022 /**
6023 *
6024 */
6025 int skipwhite(int pos);
6027 /**
6028 *
6029 */
6030 int getword(int pos, String &ret);
6032 /**
6033 *
6034 */
6035 bool sequ(int pos, const char *key);
6037 /**
6038 *
6039 */
6040 bool addIncludeFile(FileRec *frec, const String &fname);
6042 /**
6043 *
6044 */
6045 bool scanFile(const String &fname, FileRec *frec);
6047 /**
6048 *
6049 */
6050 bool processDependency(FileRec *ofile, FileRec *include);
6052 /**
6053 *
6054 */
6055 String sourceDir;
6057 /**
6058 *
6059 */
6060 std::vector<String> fileList;
6062 /**
6063 *
6064 */
6065 std::vector<String> directories;
6067 /**
6068 * A list of all files which will be processed for
6069 * dependencies.
6070 */
6071 std::map<String, FileRec *> allFiles;
6073 /**
6074 * The list of .o files, and the
6075 * dependencies upon them.
6076 */
6077 std::map<String, FileRec *> oFiles;
6079 int depFileSize;
6080 char *depFileBuf;
6082 static const int readBufSize = 8192;
6083 char readBuf[8193];//byte larger
6085 };
6091 /**
6092 * Clean up after processing. Called by the destructor, but should
6093 * also be called before the object is reused.
6094 */
6095 void DepTool::init()
6096 {
6097 sourceDir = ".";
6099 fileList.clear();
6100 directories.clear();
6102 //clear output file list
6103 std::map<String, FileRec *>::iterator iter;
6104 for (iter=oFiles.begin(); iter!=oFiles.end() ; iter++)
6105 delete iter->second;
6106 oFiles.clear();
6108 //allFiles actually contains the master copies. delete them
6109 for (iter= allFiles.begin(); iter!=allFiles.end() ; iter++)
6110 delete iter->second;
6111 allFiles.clear();
6113 }
6118 /**
6119 * Parse a full path name into path, base name, and suffix
6120 */
6121 void DepTool::parseName(const String &fullname,
6122 String &path,
6123 String &basename,
6124 String &suffix)
6125 {
6126 if (fullname.size() < 2)
6127 return;
6129 unsigned int pos = fullname.find_last_of('/');
6130 if (pos != fullname.npos && pos<fullname.size()-1)
6131 {
6132 path = fullname.substr(0, pos);
6133 pos++;
6134 basename = fullname.substr(pos, fullname.size()-pos);
6135 }
6136 else
6137 {
6138 path = "";
6139 basename = fullname;
6140 }
6142 pos = basename.find_last_of('.');
6143 if (pos != basename.npos && pos<basename.size()-1)
6144 {
6145 suffix = basename.substr(pos+1, basename.size()-pos-1);
6146 basename = basename.substr(0, pos);
6147 }
6149 //trace("parsename:%s %s %s", path.c_str(),
6150 // basename.c_str(), suffix.c_str());
6151 }
6155 /**
6156 * Generate our internal file list.
6157 */
6158 bool DepTool::createFileList()
6159 {
6161 for (unsigned int i=0 ; i<fileList.size() ; i++)
6162 {
6163 String fileName = fileList[i];
6164 //trace("## FileName:%s", fileName.c_str());
6165 String path;
6166 String basename;
6167 String sfx;
6168 parseName(fileName, path, basename, sfx);
6169 if (sfx == "cpp" || sfx == "c" || sfx == "cxx" ||
6170 sfx == "cc" || sfx == "CC")
6171 {
6172 FileRec *fe = new FileRec(FileRec::CFILE);
6173 fe->path = path;
6174 fe->baseName = basename;
6175 fe->suffix = sfx;
6176 allFiles[fileName] = fe;
6177 }
6178 else if (sfx == "h" || sfx == "hh" ||
6179 sfx == "hpp" || sfx == "hxx")
6180 {
6181 FileRec *fe = new FileRec(FileRec::HFILE);
6182 fe->path = path;
6183 fe->baseName = basename;
6184 fe->suffix = sfx;
6185 allFiles[fileName] = fe;
6186 }
6187 }
6189 if (!listDirectories(sourceDir, "", directories))
6190 return false;
6192 return true;
6193 }
6199 /**
6200 * Get a character from the buffer at pos. If out of range,
6201 * return -1 for safety
6202 */
6203 int DepTool::get(int pos)
6204 {
6205 if (pos>depFileSize)
6206 return -1;
6207 return depFileBuf[pos];
6208 }
6212 /**
6213 * Skip over all whitespace characters beginning at pos. Return
6214 * the position of the first non-whitespace character.
6215 */
6216 int DepTool::skipwhite(int pos)
6217 {
6218 while (pos < depFileSize)
6219 {
6220 int ch = get(pos);
6221 if (ch < 0)
6222 break;
6223 if (!isspace(ch))
6224 break;
6225 pos++;
6226 }
6227 return pos;
6228 }
6231 /**
6232 * Parse the buffer beginning at pos, for a word. Fill
6233 * 'ret' with the result. Return the position after the
6234 * word.
6235 */
6236 int DepTool::getword(int pos, String &ret)
6237 {
6238 while (pos < depFileSize)
6239 {
6240 int ch = get(pos);
6241 if (ch < 0)
6242 break;
6243 if (isspace(ch))
6244 break;
6245 ret.push_back((char)ch);
6246 pos++;
6247 }
6248 return pos;
6249 }
6251 /**
6252 * Return whether the sequence of characters in the buffer
6253 * beginning at pos match the key, for the length of the key
6254 */
6255 bool DepTool::sequ(int pos, const char *key)
6256 {
6257 while (*key)
6258 {
6259 if (*key != get(pos))
6260 return false;
6261 key++; pos++;
6262 }
6263 return true;
6264 }
6268 /**
6269 * Add an include file name to a file record. If the name
6270 * is not found in allFiles explicitly, try prepending include
6271 * directory names to it and try again.
6272 */
6273 bool DepTool::addIncludeFile(FileRec *frec, const String &iname)
6274 {
6275 //# if the name is an exact match to a path name
6276 //# in allFiles, like "myinc.h"
6277 std::map<String, FileRec *>::iterator iter =
6278 allFiles.find(iname);
6279 if (iter != allFiles.end()) //already exists
6280 {
6281 //h file in same dir
6282 FileRec *other = iter->second;
6283 //trace("local: '%s'", iname.c_str());
6284 frec->files[iname] = other;
6285 return true;
6286 }
6287 else
6288 {
6289 //## Ok, it was not found directly
6290 //look in other dirs
6291 std::vector<String>::iterator diter;
6292 for (diter=directories.begin() ;
6293 diter!=directories.end() ; diter++)
6294 {
6295 String dfname = *diter;
6296 dfname.append("/");
6297 dfname.append(iname);
6298 URI fullPathURI(dfname); //normalize path name
6299 String fullPath = fullPathURI.getPath();
6300 if (fullPath[0] == '/')
6301 fullPath = fullPath.substr(1);
6302 //trace("Normalized %s to %s", dfname.c_str(), fullPath.c_str());
6303 iter = allFiles.find(fullPath);
6304 if (iter != allFiles.end())
6305 {
6306 FileRec *other = iter->second;
6307 //trace("other: '%s'", iname.c_str());
6308 frec->files[fullPath] = other;
6309 return true;
6310 }
6311 }
6312 }
6313 return true;
6314 }
6318 /**
6319 * Lightly parse a file to find the #include directives. Do
6320 * a bit of state machine stuff to make sure that the directive
6321 * is valid. (Like not in a comment).
6322 */
6323 bool DepTool::scanFile(const String &fname, FileRec *frec)
6324 {
6325 String fileName;
6326 if (sourceDir.size() > 0)
6327 {
6328 fileName.append(sourceDir);
6329 fileName.append("/");
6330 }
6331 fileName.append(fname);
6332 String nativeName = getNativePath(fileName);
6333 FILE *f = fopen(nativeName.c_str(), "r");
6334 if (!f)
6335 {
6336 error("Could not open '%s' for reading", fname.c_str());
6337 return false;
6338 }
6339 String buf;
6340 while (!feof(f))
6341 {
6342 int nrbytes = fread(readBuf, 1, readBufSize, f);
6343 readBuf[nrbytes] = '\0';
6344 buf.append(readBuf);
6345 }
6346 fclose(f);
6348 depFileSize = buf.size();
6349 depFileBuf = (char *)buf.c_str();
6350 int pos = 0;
6353 while (pos < depFileSize)
6354 {
6355 //trace("p:%c", get(pos));
6357 //# Block comment
6358 if (get(pos) == '/' && get(pos+1) == '*')
6359 {
6360 pos += 2;
6361 while (pos < depFileSize)
6362 {
6363 if (get(pos) == '*' && get(pos+1) == '/')
6364 {
6365 pos += 2;
6366 break;
6367 }
6368 else
6369 pos++;
6370 }
6371 }
6372 //# Line comment
6373 else if (get(pos) == '/' && get(pos+1) == '/')
6374 {
6375 pos += 2;
6376 while (pos < depFileSize)
6377 {
6378 if (get(pos) == '\n')
6379 {
6380 pos++;
6381 break;
6382 }
6383 else
6384 pos++;
6385 }
6386 }
6387 //# #include! yaay
6388 else if (sequ(pos, "#include"))
6389 {
6390 pos += 8;
6391 pos = skipwhite(pos);
6392 String iname;
6393 pos = getword(pos, iname);
6394 if (iname.size()>2)
6395 {
6396 iname = iname.substr(1, iname.size()-2);
6397 addIncludeFile(frec, iname);
6398 }
6399 }
6400 else
6401 {
6402 pos++;
6403 }
6404 }
6406 return true;
6407 }
6411 /**
6412 * Recursively check include lists to find all files in allFiles to which
6413 * a given file is dependent.
6414 */
6415 bool DepTool::processDependency(FileRec *ofile, FileRec *include)
6416 {
6417 std::map<String, FileRec *>::iterator iter;
6418 for (iter=include->files.begin() ; iter!=include->files.end() ; iter++)
6419 {
6420 String fname = iter->first;
6421 if (ofile->files.find(fname) != ofile->files.end())
6422 {
6423 //trace("file '%s' already seen", fname.c_str());
6424 continue;
6425 }
6426 FileRec *child = iter->second;
6427 ofile->files[fname] = child;
6429 processDependency(ofile, child);
6430 }
6433 return true;
6434 }
6440 /**
6441 * Generate the file dependency list.
6442 */
6443 bool DepTool::generateDependencies()
6444 {
6445 std::map<String, FileRec *>::iterator iter;
6446 //# First pass. Scan for all includes
6447 for (iter=allFiles.begin() ; iter!=allFiles.end() ; iter++)
6448 {
6449 FileRec *frec = iter->second;
6450 if (!scanFile(iter->first, frec))
6451 {
6452 //quit?
6453 }
6454 }
6456 //# Second pass. Scan for all includes
6457 for (iter=allFiles.begin() ; iter!=allFiles.end() ; iter++)
6458 {
6459 FileRec *include = iter->second;
6460 if (include->type == FileRec::CFILE)
6461 {
6462 //String cFileName = iter->first;
6463 FileRec *ofile = new FileRec(FileRec::OFILE);
6464 ofile->path = include->path;
6465 ofile->baseName = include->baseName;
6466 ofile->suffix = include->suffix;
6467 String fname = include->path;
6468 if (fname.size()>0)
6469 fname.append("/");
6470 fname.append(include->baseName);
6471 fname.append(".o");
6472 oFiles[fname] = ofile;
6473 //add the .c file first? no, don't
6474 //ofile->files[cFileName] = include;
6476 //trace("ofile:%s", fname.c_str());
6478 processDependency(ofile, include);
6479 }
6480 }
6483 return true;
6484 }
6488 /**
6489 * High-level call to generate deps and optionally save them
6490 */
6491 bool DepTool::generateDependencies(const String &fileName)
6492 {
6493 if (!createFileList())
6494 return false;
6495 if (!generateDependencies())
6496 return false;
6497 if (!saveDepFile(fileName))
6498 return false;
6499 return true;
6500 }
6503 /**
6504 * This saves the dependency cache.
6505 */
6506 bool DepTool::saveDepFile(const String &fileName)
6507 {
6508 time_t tim;
6509 time(&tim);
6511 FILE *f = fopen(fileName.c_str(), "w");
6512 if (!f)
6513 {
6514 trace("cannot open '%s' for writing", fileName.c_str());
6515 }
6516 fprintf(f, "<?xml version='1.0'?>\n");
6517 fprintf(f, "<!--\n");
6518 fprintf(f, "########################################################\n");
6519 fprintf(f, "## File: build.dep\n");
6520 fprintf(f, "## Generated by BuildTool at :%s", ctime(&tim));
6521 fprintf(f, "########################################################\n");
6522 fprintf(f, "-->\n");
6524 fprintf(f, "<dependencies source='%s'>\n\n", sourceDir.c_str());
6525 std::map<String, FileRec *>::iterator iter;
6526 for (iter=oFiles.begin() ; iter!=oFiles.end() ; iter++)
6527 {
6528 FileRec *frec = iter->second;
6529 if (frec->type == FileRec::OFILE)
6530 {
6531 fprintf(f, "<object path='%s' name='%s' suffix='%s'>\n",
6532 frec->path.c_str(), frec->baseName.c_str(), frec->suffix.c_str());
6533 std::map<String, FileRec *>::iterator citer;
6534 for (citer=frec->files.begin() ; citer!=frec->files.end() ; citer++)
6535 {
6536 String cfname = citer->first;
6537 fprintf(f, " <dep name='%s'/>\n", cfname.c_str());
6538 }
6539 fprintf(f, "</object>\n\n");
6540 }
6541 }
6543 fprintf(f, "</dependencies>\n");
6544 fprintf(f, "\n");
6545 fprintf(f, "<!--\n");
6546 fprintf(f, "########################################################\n");
6547 fprintf(f, "## E N D\n");
6548 fprintf(f, "########################################################\n");
6549 fprintf(f, "-->\n");
6551 fclose(f);
6553 return true;
6554 }
6559 /**
6560 * This loads the dependency cache.
6561 */
6562 std::vector<DepRec> DepTool::loadDepFile(const String &depFile)
6563 {
6564 std::vector<DepRec> result;
6566 Parser parser;
6567 Element *root = parser.parseFile(depFile.c_str());
6568 if (!root)
6569 {
6570 //error("Could not open %s for reading", depFile.c_str());
6571 return result;
6572 }
6574 if (root->getChildren().size()==0 ||
6575 root->getChildren()[0]->getName()!="dependencies")
6576 {
6577 error("loadDepFile: main xml element should be <dependencies>");
6578 delete root;
6579 return result;
6580 }
6582 //########## Start parsing
6583 Element *depList = root->getChildren()[0];
6585 std::vector<Element *> objects = depList->getChildren();
6586 for (unsigned int i=0 ; i<objects.size() ; i++)
6587 {
6588 Element *objectElem = objects[i];
6589 String tagName = objectElem->getName();
6590 if (tagName != "object")
6591 {
6592 error("loadDepFile: <dependencies> should have only <object> children");
6593 return result;
6594 }
6596 String objName = objectElem->getAttribute("name");
6597 //trace("object:%s", objName.c_str());
6598 DepRec depObject(objName);
6599 depObject.path = objectElem->getAttribute("path");
6600 depObject.suffix = objectElem->getAttribute("suffix");
6601 //########## DESCRIPTION
6602 std::vector<Element *> depElems = objectElem->getChildren();
6603 for (unsigned int i=0 ; i<depElems.size() ; i++)
6604 {
6605 Element *depElem = depElems[i];
6606 tagName = depElem->getName();
6607 if (tagName != "dep")
6608 {
6609 error("loadDepFile: <object> should have only <dep> children");
6610 return result;
6611 }
6612 String depName = depElem->getAttribute("name");
6613 //trace(" dep:%s", depName.c_str());
6614 depObject.files.push_back(depName);
6615 }
6617 //Insert into the result list, in a sorted manner
6618 bool inserted = false;
6619 std::vector<DepRec>::iterator iter;
6620 for (iter = result.begin() ; iter != result.end() ; iter++)
6621 {
6622 String vpath = iter->path;
6623 vpath.append("/");
6624 vpath.append(iter->name);
6625 String opath = depObject.path;
6626 opath.append("/");
6627 opath.append(depObject.name);
6628 if (vpath > opath)
6629 {
6630 inserted = true;
6631 iter = result.insert(iter, depObject);
6632 break;
6633 }
6634 }
6635 if (!inserted)
6636 result.push_back(depObject);
6637 }
6639 delete root;
6641 return result;
6642 }
6645 /**
6646 * This loads the dependency cache.
6647 */
6648 std::vector<DepRec> DepTool::getDepFile(const String &depFile,
6649 bool forceRefresh)
6650 {
6651 std::vector<DepRec> result;
6652 if (forceRefresh)
6653 {
6654 generateDependencies(depFile);
6655 result = loadDepFile(depFile);
6656 }
6657 else
6658 {
6659 //try once
6660 result = loadDepFile(depFile);
6661 if (result.size() == 0)
6662 {
6663 //fail? try again
6664 generateDependencies(depFile);
6665 result = loadDepFile(depFile);
6666 }
6667 }
6668 return result;
6669 }
6674 //########################################################################
6675 //# T A S K
6676 //########################################################################
6677 //forward decl
6678 class Target;
6679 class Make;
6681 /**
6682 *
6683 */
6684 class Task : public MakeBase
6685 {
6687 public:
6689 typedef enum
6690 {
6691 TASK_NONE,
6692 TASK_CC,
6693 TASK_COPY,
6694 TASK_CXXTEST_PART,
6695 TASK_CXXTEST_ROOT,
6696 TASK_CXXTEST_RUN,
6697 TASK_DELETE,
6698 TASK_ECHO,
6699 TASK_JAR,
6700 TASK_JAVAC,
6701 TASK_LINK,
6702 TASK_MAKEFILE,
6703 TASK_MKDIR,
6704 TASK_MSGFMT,
6705 TASK_PKG_CONFIG,
6706 TASK_RANLIB,
6707 TASK_RC,
6708 TASK_SHAREDLIB,
6709 TASK_STATICLIB,
6710 TASK_STRIP,
6711 TASK_TOUCH,
6712 TASK_TSTAMP
6713 } TaskType;
6716 /**
6717 *
6718 */
6719 Task(MakeBase &par) : parent(par)
6720 { init(); }
6722 /**
6723 *
6724 */
6725 Task(const Task &other) : parent(other.parent)
6726 { init(); assign(other); }
6728 /**
6729 *
6730 */
6731 Task &operator=(const Task &other)
6732 { assign(other); return *this; }
6734 /**
6735 *
6736 */
6737 virtual ~Task()
6738 { }
6741 /**
6742 *
6743 */
6744 virtual MakeBase &getParent()
6745 { return parent; }
6747 /**
6748 *
6749 */
6750 virtual int getType()
6751 { return type; }
6753 /**
6754 *
6755 */
6756 virtual void setType(int val)
6757 { type = val; }
6759 /**
6760 *
6761 */
6762 virtual String getName()
6763 { return name; }
6765 /**
6766 *
6767 */
6768 virtual bool execute()
6769 { return true; }
6771 /**
6772 *
6773 */
6774 virtual bool parse(Element *elem)
6775 { return true; }
6777 /**
6778 *
6779 */
6780 Task *createTask(Element *elem, int lineNr);
6783 protected:
6785 void init()
6786 {
6787 type = TASK_NONE;
6788 name = "none";
6789 }
6791 void assign(const Task &other)
6792 {
6793 type = other.type;
6794 name = other.name;
6795 }
6797 /**
6798 * Show task status
6799 */
6800 void taskstatus(const char *fmt, ...)
6801 {
6802 va_list args;
6803 va_start(args,fmt);
6804 fprintf(stdout, " %s : ", name.c_str());
6805 vfprintf(stdout, fmt, args);
6806 fprintf(stdout, "\n");
6807 va_end(args) ;
6808 }
6810 String getAttribute(Element *elem, const String &attrName)
6811 {
6812 String str;
6813 return str;
6814 }
6816 MakeBase &parent;
6818 int type;
6820 String name;
6821 };
6825 /**
6826 * This task runs the C/C++ compiler. The compiler is invoked
6827 * for all .c or .cpp files which are newer than their correcsponding
6828 * .o files.
6829 */
6830 class TaskCC : public Task
6831 {
6832 public:
6834 TaskCC(MakeBase &par) : Task(par)
6835 {
6836 type = TASK_CC;
6837 name = "cc";
6838 }
6840 virtual ~TaskCC()
6841 {}
6843 virtual bool isExcludedInc(const String &dirname)
6844 {
6845 for (unsigned int i=0 ; i<excludeInc.size() ; i++)
6846 {
6847 String fname = excludeInc[i];
6848 if (fname == dirname)
6849 return true;
6850 }
6851 return false;
6852 }
6854 virtual bool execute()
6855 {
6856 //evaluate our parameters
6857 String command = parent.eval(commandOpt, "gcc");
6858 String ccCommand = parent.eval(ccCommandOpt, "gcc");
6859 String cxxCommand = parent.eval(cxxCommandOpt, "g++");
6860 String source = parent.eval(sourceOpt, ".");
6861 String dest = parent.eval(destOpt, ".");
6862 String flags = parent.eval(flagsOpt, "");
6863 String defines = parent.eval(definesOpt, "");
6864 String includes = parent.eval(includesOpt, "");
6865 bool continueOnError = parent.evalBool(continueOnErrorOpt, true);
6866 bool refreshCache = parent.evalBool(refreshCacheOpt, false);
6868 if (!listFiles(parent, fileSet))
6869 return false;
6871 FILE *f = NULL;
6872 f = fopen("compile.lst", "w");
6874 //refreshCache is probably false here, unless specified otherwise
6875 String fullName = parent.resolve("build.dep");
6876 if (refreshCache || isNewerThan(parent.getURI().getPath(), fullName))
6877 {
6878 taskstatus("regenerating C/C++ dependency cache");
6879 refreshCache = true;
6880 }
6882 DepTool depTool;
6883 depTool.setSourceDirectory(source);
6884 depTool.setFileList(fileSet.getFiles());
6885 std::vector<DepRec> deps =
6886 depTool.getDepFile("build.dep", refreshCache);
6888 String incs;
6889 incs.append("-I");
6890 incs.append(parent.resolve("."));
6891 incs.append(" ");
6892 if (includes.size()>0)
6893 {
6894 incs.append(includes);
6895 incs.append(" ");
6896 }
6897 std::set<String> paths;
6898 std::vector<DepRec>::iterator viter;
6899 for (viter=deps.begin() ; viter!=deps.end() ; viter++)
6900 {
6901 DepRec dep = *viter;
6902 if (dep.path.size()>0)
6903 paths.insert(dep.path);
6904 }
6905 if (source.size()>0)
6906 {
6907 incs.append(" -I");
6908 incs.append(parent.resolve(source));
6909 incs.append(" ");
6910 }
6911 std::set<String>::iterator setIter;
6912 for (setIter=paths.begin() ; setIter!=paths.end() ; setIter++)
6913 {
6914 String dirName = *setIter;
6915 //check excludeInc to see if we dont want to include this dir
6916 if (isExcludedInc(dirName))
6917 continue;
6918 incs.append(" -I");
6919 String dname;
6920 if (source.size()>0)
6921 {
6922 dname.append(source);
6923 dname.append("/");
6924 }
6925 dname.append(dirName);
6926 incs.append(parent.resolve(dname));
6927 }
6929 /**
6930 * Compile each of the C files that need it
6931 */
6932 bool errorOccurred = false;
6933 std::vector<String> cfiles;
6934 for (viter=deps.begin() ; viter!=deps.end() ; viter++)
6935 {
6936 DepRec dep = *viter;
6938 //## Select command
6939 String sfx = dep.suffix;
6940 String command = ccCommand;
6941 if (sfx == "cpp" || sfx == "cxx" || sfx == "c++" ||
6942 sfx == "cc" || sfx == "CC")
6943 command = cxxCommand;
6945 //## Make paths
6946 String destPath = dest;
6947 String srcPath = source;
6948 if (dep.path.size()>0)
6949 {
6950 destPath.append("/");
6951 destPath.append(dep.path);
6952 srcPath.append("/");
6953 srcPath.append(dep.path);
6954 }
6955 //## Make sure destination directory exists
6956 if (!createDirectory(destPath))
6957 return false;
6959 //## Check whether it needs to be done
6960 String destName;
6961 if (destPath.size()>0)
6962 {
6963 destName.append(destPath);
6964 destName.append("/");
6965 }
6966 destName.append(dep.name);
6967 destName.append(".o");
6968 String destFullName = parent.resolve(destName);
6969 String srcName;
6970 if (srcPath.size()>0)
6971 {
6972 srcName.append(srcPath);
6973 srcName.append("/");
6974 }
6975 srcName.append(dep.name);
6976 srcName.append(".");
6977 srcName.append(dep.suffix);
6978 String srcFullName = parent.resolve(srcName);
6979 bool compileMe = false;
6980 //# First we check if the source is newer than the .o
6981 if (isNewerThan(srcFullName, destFullName))
6982 {
6983 taskstatus("compile of %s required by source: %s",
6984 destFullName.c_str(), srcFullName.c_str());
6985 compileMe = true;
6986 }
6987 else
6988 {
6989 //# secondly, we check if any of the included dependencies
6990 //# of the .c/.cpp is newer than the .o
6991 for (unsigned int i=0 ; i<dep.files.size() ; i++)
6992 {
6993 String depName;
6994 if (source.size()>0)
6995 {
6996 depName.append(source);
6997 depName.append("/");
6998 }
6999 depName.append(dep.files[i]);
7000 String depFullName = parent.resolve(depName);
7001 bool depRequires = isNewerThan(depFullName, destFullName);
7002 //trace("%d %s %s\n", depRequires,
7003 // destFullName.c_str(), depFullName.c_str());
7004 if (depRequires)
7005 {
7006 taskstatus("compile of %s required by included: %s",
7007 destFullName.c_str(), depFullName.c_str());
7008 compileMe = true;
7009 break;
7010 }
7011 }
7012 }
7013 if (!compileMe)
7014 {
7015 continue;
7016 }
7018 //## Assemble the command
7019 String cmd = command;
7020 cmd.append(" -c ");
7021 cmd.append(flags);
7022 cmd.append(" ");
7023 cmd.append(defines);
7024 cmd.append(" ");
7025 cmd.append(incs);
7026 cmd.append(" ");
7027 cmd.append(srcFullName);
7028 cmd.append(" -o ");
7029 cmd.append(destFullName);
7031 //## Execute the command
7033 String outString, errString;
7034 bool ret = executeCommand(cmd.c_str(), "", outString, errString);
7036 if (f)
7037 {
7038 fprintf(f, "########################### File : %s\n",
7039 srcFullName.c_str());
7040 fprintf(f, "#### COMMAND ###\n");
7041 int col = 0;
7042 for (unsigned int i = 0 ; i < cmd.size() ; i++)
7043 {
7044 char ch = cmd[i];
7045 if (isspace(ch) && col > 63)
7046 {
7047 fputc('\n', f);
7048 col = 0;
7049 }
7050 else
7051 {
7052 fputc(ch, f);
7053 col++;
7054 }
7055 if (col > 76)
7056 {
7057 fputc('\n', f);
7058 col = 0;
7059 }
7060 }
7061 fprintf(f, "\n");
7062 fprintf(f, "#### STDOUT ###\n%s\n", outString.c_str());
7063 fprintf(f, "#### STDERR ###\n%s\n\n", errString.c_str());
7064 fflush(f);
7065 }
7066 if (!ret)
7067 {
7068 error("problem compiling: %s", errString.c_str());
7069 errorOccurred = true;
7070 }
7071 if (errorOccurred && !continueOnError)
7072 break;
7074 removeFromStatCache(getNativePath(destFullName));
7075 }
7077 if (f)
7078 {
7079 fclose(f);
7080 }
7082 return !errorOccurred;
7083 }
7086 virtual bool parse(Element *elem)
7087 {
7088 String s;
7089 if (!parent.getAttribute(elem, "command", commandOpt))
7090 return false;
7091 if (commandOpt.size()>0)
7092 { cxxCommandOpt = ccCommandOpt = commandOpt; }
7093 if (!parent.getAttribute(elem, "cc", ccCommandOpt))
7094 return false;
7095 if (!parent.getAttribute(elem, "cxx", cxxCommandOpt))
7096 return false;
7097 if (!parent.getAttribute(elem, "destdir", destOpt))
7098 return false;
7099 if (!parent.getAttribute(elem, "continueOnError", continueOnErrorOpt))
7100 return false;
7101 if (!parent.getAttribute(elem, "refreshCache", refreshCacheOpt))
7102 return false;
7104 std::vector<Element *> children = elem->getChildren();
7105 for (unsigned int i=0 ; i<children.size() ; i++)
7106 {
7107 Element *child = children[i];
7108 String tagName = child->getName();
7109 if (tagName == "flags")
7110 {
7111 if (!parent.getValue(child, flagsOpt))
7112 return false;
7113 flagsOpt = strip(flagsOpt);
7114 }
7115 else if (tagName == "includes")
7116 {
7117 if (!parent.getValue(child, includesOpt))
7118 return false;
7119 includesOpt = strip(includesOpt);
7120 }
7121 else if (tagName == "defines")
7122 {
7123 if (!parent.getValue(child, definesOpt))
7124 return false;
7125 definesOpt = strip(definesOpt);
7126 }
7127 else if (tagName == "fileset")
7128 {
7129 if (!parseFileSet(child, parent, fileSet))
7130 return false;
7131 sourceOpt = fileSet.getDirectory();
7132 }
7133 else if (tagName == "excludeinc")
7134 {
7135 if (!parseFileList(child, parent, excludeInc))
7136 return false;
7137 }
7138 }
7140 return true;
7141 }
7143 protected:
7145 String commandOpt;
7146 String ccCommandOpt;
7147 String cxxCommandOpt;
7148 String sourceOpt;
7149 String destOpt;
7150 String flagsOpt;
7151 String definesOpt;
7152 String includesOpt;
7153 String continueOnErrorOpt;
7154 String refreshCacheOpt;
7155 FileSet fileSet;
7156 FileList excludeInc;
7158 };
7162 /**
7163 *
7164 */
7165 class TaskCopy : public Task
7166 {
7167 public:
7169 typedef enum
7170 {
7171 CP_NONE,
7172 CP_TOFILE,
7173 CP_TODIR
7174 } CopyType;
7176 TaskCopy(MakeBase &par) : Task(par)
7177 {
7178 type = TASK_COPY;
7179 name = "copy";
7180 cptype = CP_NONE;
7181 haveFileSet = false;
7182 }
7184 virtual ~TaskCopy()
7185 {}
7187 virtual bool execute()
7188 {
7189 String fileName = parent.eval(fileNameOpt , ".");
7190 String toFileName = parent.eval(toFileNameOpt , ".");
7191 String toDirName = parent.eval(toDirNameOpt , ".");
7192 bool verbose = parent.evalBool(verboseOpt, false);
7193 switch (cptype)
7194 {
7195 case CP_TOFILE:
7196 {
7197 if (fileName.size()>0)
7198 {
7199 taskstatus("%s to %s",
7200 fileName.c_str(), toFileName.c_str());
7201 String fullSource = parent.resolve(fileName);
7202 String fullDest = parent.resolve(toFileName);
7203 if (verbose)
7204 taskstatus("copy %s to file %s", fullSource.c_str(),
7205 fullDest.c_str());
7206 if (!isRegularFile(fullSource))
7207 {
7208 error("copy : file %s does not exist", fullSource.c_str());
7209 return false;
7210 }
7211 if (!isNewerThan(fullSource, fullDest))
7212 {
7213 taskstatus("skipped");
7214 return true;
7215 }
7216 if (!copyFile(fullSource, fullDest))
7217 return false;
7218 taskstatus("1 file copied");
7219 }
7220 return true;
7221 }
7222 case CP_TODIR:
7223 {
7224 if (haveFileSet)
7225 {
7226 if (!listFiles(parent, fileSet))
7227 return false;
7228 String fileSetDir = parent.eval(fileSet.getDirectory(), ".");
7230 taskstatus("%s to %s",
7231 fileSetDir.c_str(), toDirName.c_str());
7233 int nrFiles = 0;
7234 for (unsigned int i=0 ; i<fileSet.size() ; i++)
7235 {
7236 String fileName = fileSet[i];
7238 String sourcePath;
7239 if (fileSetDir.size()>0)
7240 {
7241 sourcePath.append(fileSetDir);
7242 sourcePath.append("/");
7243 }
7244 sourcePath.append(fileName);
7245 String fullSource = parent.resolve(sourcePath);
7247 //Get the immediate parent directory's base name
7248 String baseFileSetDir = fileSetDir;
7249 unsigned int pos = baseFileSetDir.find_last_of('/');
7250 if (pos!=baseFileSetDir.npos &&
7251 pos < baseFileSetDir.size()-1)
7252 baseFileSetDir =
7253 baseFileSetDir.substr(pos+1,
7254 baseFileSetDir.size());
7255 //Now make the new path
7256 String destPath;
7257 if (toDirName.size()>0)
7258 {
7259 destPath.append(toDirName);
7260 destPath.append("/");
7261 }
7262 if (baseFileSetDir.size()>0)
7263 {
7264 destPath.append(baseFileSetDir);
7265 destPath.append("/");
7266 }
7267 destPath.append(fileName);
7268 String fullDest = parent.resolve(destPath);
7269 //trace("fileName:%s", fileName.c_str());
7270 if (verbose)
7271 taskstatus("copy %s to new dir : %s",
7272 fullSource.c_str(), fullDest.c_str());
7273 if (!isNewerThan(fullSource, fullDest))
7274 {
7275 if (verbose)
7276 taskstatus("copy skipping %s", fullSource.c_str());
7277 continue;
7278 }
7279 if (!copyFile(fullSource, fullDest))
7280 return false;
7281 nrFiles++;
7282 }
7283 taskstatus("%d file(s) copied", nrFiles);
7284 }
7285 else //file source
7286 {
7287 //For file->dir we want only the basename of
7288 //the source appended to the dest dir
7289 taskstatus("%s to %s",
7290 fileName.c_str(), toDirName.c_str());
7291 String baseName = fileName;
7292 unsigned int pos = baseName.find_last_of('/');
7293 if (pos!=baseName.npos && pos<baseName.size()-1)
7294 baseName = baseName.substr(pos+1, baseName.size());
7295 String fullSource = parent.resolve(fileName);
7296 String destPath;
7297 if (toDirName.size()>0)
7298 {
7299 destPath.append(toDirName);
7300 destPath.append("/");
7301 }
7302 destPath.append(baseName);
7303 String fullDest = parent.resolve(destPath);
7304 if (verbose)
7305 taskstatus("file %s to new dir : %s", fullSource.c_str(),
7306 fullDest.c_str());
7307 if (!isRegularFile(fullSource))
7308 {
7309 error("copy : file %s does not exist", fullSource.c_str());
7310 return false;
7311 }
7312 if (!isNewerThan(fullSource, fullDest))
7313 {
7314 taskstatus("skipped");
7315 return true;
7316 }
7317 if (!copyFile(fullSource, fullDest))
7318 return false;
7319 taskstatus("1 file copied");
7320 }
7321 return true;
7322 }
7323 }
7324 return true;
7325 }
7328 virtual bool parse(Element *elem)
7329 {
7330 if (!parent.getAttribute(elem, "file", fileNameOpt))
7331 return false;
7332 if (!parent.getAttribute(elem, "tofile", toFileNameOpt))
7333 return false;
7334 if (toFileNameOpt.size() > 0)
7335 cptype = CP_TOFILE;
7336 if (!parent.getAttribute(elem, "todir", toDirNameOpt))
7337 return false;
7338 if (toDirNameOpt.size() > 0)
7339 cptype = CP_TODIR;
7340 if (!parent.getAttribute(elem, "verbose", verboseOpt))
7341 return false;
7343 haveFileSet = false;
7345 std::vector<Element *> children = elem->getChildren();
7346 for (unsigned int i=0 ; i<children.size() ; i++)
7347 {
7348 Element *child = children[i];
7349 String tagName = child->getName();
7350 if (tagName == "fileset")
7351 {
7352 if (!parseFileSet(child, parent, fileSet))
7353 {
7354 error("problem getting fileset");
7355 return false;
7356 }
7357 haveFileSet = true;
7358 }
7359 }
7361 //Perform validity checks
7362 if (fileNameOpt.size()>0 && fileSet.size()>0)
7363 {
7364 error("<copy> can only have one of : file= and <fileset>");
7365 return false;
7366 }
7367 if (toFileNameOpt.size()>0 && toDirNameOpt.size()>0)
7368 {
7369 error("<copy> can only have one of : tofile= or todir=");
7370 return false;
7371 }
7372 if (haveFileSet && toDirNameOpt.size()==0)
7373 {
7374 error("a <copy> task with a <fileset> must have : todir=");
7375 return false;
7376 }
7377 if (cptype == CP_TOFILE && fileNameOpt.size()==0)
7378 {
7379 error("<copy> tofile= must be associated with : file=");
7380 return false;
7381 }
7382 if (cptype == CP_TODIR && fileNameOpt.size()==0 && !haveFileSet)
7383 {
7384 error("<copy> todir= must be associated with : file= or <fileset>");
7385 return false;
7386 }
7388 return true;
7389 }
7391 private:
7393 int cptype;
7394 bool haveFileSet;
7396 FileSet fileSet;
7397 String fileNameOpt;
7398 String toFileNameOpt;
7399 String toDirNameOpt;
7400 String verboseOpt;
7401 };
7404 /**
7405 * Generate CxxTest files
7406 */
7407 class TaskCxxTestPart: public Task
7408 {
7409 public:
7411 TaskCxxTestPart(MakeBase &par) : Task(par)
7412 {
7413 type = TASK_CXXTEST_PART;
7414 name = "cxxtestpart";
7415 }
7417 virtual ~TaskCxxTestPart()
7418 {}
7420 virtual bool execute()
7421 {
7422 if (!listFiles(parent, fileSet))
7423 return false;
7424 String fileSetDir = parent.eval(fileSet.getDirectory(), ".");
7426 String fullDest = parent.resolve(parent.eval(destPathOpt, "."));
7427 String cmd = parent.eval(commandOpt, "cxxtestgen.py");
7428 cmd.append(" --part -o ");
7429 cmd.append(fullDest);
7431 unsigned int newFiles = 0;
7432 for (unsigned int i=0 ; i<fileSet.size() ; i++)
7433 {
7434 String fileName = fileSet[i];
7435 if (getSuffix(fileName) != "h")
7436 continue;
7437 String sourcePath;
7438 if (fileSetDir.size()>0)
7439 {
7440 sourcePath.append(fileSetDir);
7441 sourcePath.append("/");
7442 }
7443 sourcePath.append(fileName);
7444 String fullSource = parent.resolve(sourcePath);
7446 cmd.append(" ");
7447 cmd.append(fullSource);
7448 if (isNewerThan(fullSource, fullDest)) newFiles++;
7449 }
7451 if (newFiles>0) {
7452 size_t const lastSlash = fullDest.find_last_of('/');
7453 if (lastSlash != fullDest.npos) {
7454 String directory(fullDest, 0, lastSlash);
7455 if (!createDirectory(directory))
7456 return false;
7457 }
7459 String outString, errString;
7460 if (!executeCommand(cmd.c_str(), "", outString, errString))
7461 {
7462 error("<cxxtestpart> problem: %s", errString.c_str());
7463 return false;
7464 }
7465 removeFromStatCache(getNativePath(fullDest));
7466 }
7468 return true;
7469 }
7471 virtual bool parse(Element *elem)
7472 {
7473 if (!parent.getAttribute(elem, "command", commandOpt))
7474 return false;
7475 if (!parent.getAttribute(elem, "out", destPathOpt))
7476 return false;
7478 std::vector<Element *> children = elem->getChildren();
7479 for (unsigned int i=0 ; i<children.size() ; i++)
7480 {
7481 Element *child = children[i];
7482 String tagName = child->getName();
7483 if (tagName == "fileset")
7484 {
7485 if (!parseFileSet(child, parent, fileSet))
7486 return false;
7487 }
7488 }
7489 return true;
7490 }
7492 private:
7494 String commandOpt;
7495 String destPathOpt;
7496 FileSet fileSet;
7498 };
7501 /**
7502 * Generate the CxxTest root file
7503 */
7504 class TaskCxxTestRoot: public Task
7505 {
7506 public:
7508 TaskCxxTestRoot(MakeBase &par) : Task(par)
7509 {
7510 type = TASK_CXXTEST_ROOT;
7511 name = "cxxtestroot";
7512 }
7514 virtual ~TaskCxxTestRoot()
7515 {}
7517 virtual bool execute()
7518 {
7519 if (!listFiles(parent, fileSet))
7520 return false;
7521 String fileSetDir = parent.eval(fileSet.getDirectory(), ".");
7522 unsigned int newFiles = 0;
7524 String fullDest = parent.resolve(parent.eval(destPathOpt, "."));
7525 String cmd = parent.eval(commandOpt, "cxxtestgen.py");
7526 cmd.append(" --root -o ");
7527 cmd.append(fullDest);
7528 String templateFile = parent.eval(templateFileOpt, "");
7529 if (templateFile.size()>0) {
7530 String fullTemplate = parent.resolve(templateFile);
7531 cmd.append(" --template=");
7532 cmd.append(fullTemplate);
7533 if (isNewerThan(fullTemplate, fullDest)) newFiles++;
7534 }
7536 for (unsigned int i=0 ; i<fileSet.size() ; i++)
7537 {
7538 String fileName = fileSet[i];
7539 if (getSuffix(fileName) != "h")
7540 continue;
7541 String sourcePath;
7542 if (fileSetDir.size()>0)
7543 {
7544 sourcePath.append(fileSetDir);
7545 sourcePath.append("/");
7546 }
7547 sourcePath.append(fileName);
7548 String fullSource = parent.resolve(sourcePath);
7550 cmd.append(" ");
7551 cmd.append(fullSource);
7552 if (isNewerThan(fullSource, fullDest)) newFiles++;
7553 }
7555 if (newFiles>0) {
7556 size_t const lastSlash = fullDest.find_last_of('/');
7557 if (lastSlash != fullDest.npos) {
7558 String directory(fullDest, 0, lastSlash);
7559 if (!createDirectory(directory))
7560 return false;
7561 }
7563 String outString, errString;
7564 if (!executeCommand(cmd.c_str(), "", outString, errString))
7565 {
7566 error("<cxxtestroot> problem: %s", errString.c_str());
7567 return false;
7568 }
7569 removeFromStatCache(getNativePath(fullDest));
7570 }
7572 return true;
7573 }
7575 virtual bool parse(Element *elem)
7576 {
7577 if (!parent.getAttribute(elem, "command", commandOpt))
7578 return false;
7579 if (!parent.getAttribute(elem, "template", templateFileOpt))
7580 return false;
7581 if (!parent.getAttribute(elem, "out", destPathOpt))
7582 return false;
7584 std::vector<Element *> children = elem->getChildren();
7585 for (unsigned int i=0 ; i<children.size() ; i++)
7586 {
7587 Element *child = children[i];
7588 String tagName = child->getName();
7589 if (tagName == "fileset")
7590 {
7591 if (!parseFileSet(child, parent, fileSet))
7592 return false;
7593 }
7594 }
7595 return true;
7596 }
7598 private:
7600 String commandOpt;
7601 String templateFileOpt;
7602 String destPathOpt;
7603 FileSet fileSet;
7605 };
7608 /**
7609 * Execute the CxxTest test executable
7610 */
7611 class TaskCxxTestRun: public Task
7612 {
7613 public:
7615 TaskCxxTestRun(MakeBase &par) : Task(par)
7616 {
7617 type = TASK_CXXTEST_RUN;
7618 name = "cxxtestrun";
7619 }
7621 virtual ~TaskCxxTestRun()
7622 {}
7624 virtual bool execute()
7625 {
7626 unsigned int newFiles = 0;
7628 String workingDir = parent.resolve(parent.eval(workingDirOpt, "inkscape"));
7629 String rawCmd = parent.eval(commandOpt, "build/cxxtests");
7631 String cmdExe;
7632 if (fileExists(rawCmd)) {
7633 cmdExe = rawCmd;
7634 } else if (fileExists(rawCmd + ".exe")) {
7635 cmdExe = rawCmd + ".exe";
7636 } else {
7637 error("<cxxtestrun> problem: cxxtests executable not found! (command=\"%s\")", rawCmd.c_str());
7638 }
7639 // Note that the log file names are based on the exact name used to call cxxtests (it uses argv[0] + ".log"/".xml")
7640 if (isNewerThan(cmdExe, rawCmd + ".log") || isNewerThan(cmdExe, rawCmd + ".xml")) newFiles++;
7642 // Prepend the necessary ../'s
7643 String cmd = rawCmd;
7644 unsigned int workingDirDepth = 0;
7645 bool wasSlash = true;
7646 for(size_t i=0; i<workingDir.size(); i++) {
7647 // This assumes no . and .. parts
7648 if (wasSlash && workingDir[i]!='/') workingDirDepth++;
7649 wasSlash = workingDir[i] == '/';
7650 }
7651 for(size_t i=0; i<workingDirDepth; i++) {
7652 cmd = "../" + cmd;
7653 }
7655 if (newFiles>0) {
7656 char olddir[1024];
7657 if (workingDir.size()>0) {
7658 // TODO: Double-check usage of getcwd and handle chdir errors
7659 getcwd(olddir, 1024);
7660 chdir(workingDir.c_str());
7661 }
7663 String outString;
7664 if (!executeCommand(cmd.c_str(), "", outString, outString))
7665 {
7666 error("<cxxtestrun> problem: %s", outString.c_str());
7667 return false;
7668 }
7670 if (workingDir.size()>0) {
7671 // TODO: Handle errors?
7672 chdir(olddir);
7673 }
7675 removeFromStatCache(getNativePath(cmd + ".log"));
7676 removeFromStatCache(getNativePath(cmd + ".xml"));
7677 }
7679 return true;
7680 }
7682 virtual bool parse(Element *elem)
7683 {
7684 if (!parent.getAttribute(elem, "command", commandOpt))
7685 return false;
7686 if (!parent.getAttribute(elem, "workingdir", workingDirOpt))
7687 return false;
7688 return true;
7689 }
7691 private:
7693 String commandOpt;
7694 String workingDirOpt;
7696 };
7699 /**
7700 *
7701 */
7702 class TaskDelete : public Task
7703 {
7704 public:
7706 typedef enum
7707 {
7708 DEL_FILE,
7709 DEL_DIR,
7710 DEL_FILESET
7711 } DeleteType;
7713 TaskDelete(MakeBase &par) : Task(par)
7714 {
7715 type = TASK_DELETE;
7716 name = "delete";
7717 delType = DEL_FILE;
7718 }
7720 virtual ~TaskDelete()
7721 {}
7723 virtual bool execute()
7724 {
7725 String dirName = parent.eval(dirNameOpt, ".");
7726 String fileName = parent.eval(fileNameOpt, ".");
7727 bool verbose = parent.evalBool(verboseOpt, false);
7728 bool quiet = parent.evalBool(quietOpt, false);
7729 bool failOnError = parent.evalBool(failOnErrorOpt, true);
7730 switch (delType)
7731 {
7732 case DEL_FILE:
7733 {
7734 taskstatus("file: %s", fileName.c_str());
7735 String fullName = parent.resolve(fileName);
7736 char *fname = (char *)fullName.c_str();
7737 if (!quiet && verbose)
7738 taskstatus("path: %s", fname);
7739 if (failOnError && !removeFile(fullName))
7740 {
7741 //error("Could not delete file '%s'", fullName.c_str());
7742 return false;
7743 }
7744 return true;
7745 }
7746 case DEL_DIR:
7747 {
7748 taskstatus("dir: %s", dirName.c_str());
7749 String fullDir = parent.resolve(dirName);
7750 if (!quiet && verbose)
7751 taskstatus("path: %s", fullDir.c_str());
7752 if (failOnError && !removeDirectory(fullDir))
7753 {
7754 //error("Could not delete directory '%s'", fullDir.c_str());
7755 return false;
7756 }
7757 return true;
7758 }
7759 }
7760 return true;
7761 }
7763 virtual bool parse(Element *elem)
7764 {
7765 if (!parent.getAttribute(elem, "file", fileNameOpt))
7766 return false;
7767 if (fileNameOpt.size() > 0)
7768 delType = DEL_FILE;
7769 if (!parent.getAttribute(elem, "dir", dirNameOpt))
7770 return false;
7771 if (dirNameOpt.size() > 0)
7772 delType = DEL_DIR;
7773 if (fileNameOpt.size()>0 && dirNameOpt.size()>0)
7774 {
7775 error("<delete> can have one attribute of file= or dir=");
7776 return false;
7777 }
7778 if (fileNameOpt.size()==0 && dirNameOpt.size()==0)
7779 {
7780 error("<delete> must have one attribute of file= or dir=");
7781 return false;
7782 }
7783 if (!parent.getAttribute(elem, "verbose", verboseOpt))
7784 return false;
7785 if (!parent.getAttribute(elem, "quiet", quietOpt))
7786 return false;
7787 if (!parent.getAttribute(elem, "failonerror", failOnErrorOpt))
7788 return false;
7789 return true;
7790 }
7792 private:
7794 int delType;
7795 String dirNameOpt;
7796 String fileNameOpt;
7797 String verboseOpt;
7798 String quietOpt;
7799 String failOnErrorOpt;
7800 };
7803 /**
7804 * Send a message to stdout
7805 */
7806 class TaskEcho : public Task
7807 {
7808 public:
7810 TaskEcho(MakeBase &par) : Task(par)
7811 { type = TASK_ECHO; name = "echo"; }
7813 virtual ~TaskEcho()
7814 {}
7816 virtual bool execute()
7817 {
7818 //let message have priority over text
7819 String message = parent.eval(messageOpt, "");
7820 String text = parent.eval(textOpt, "");
7821 if (message.size() > 0)
7822 {
7823 fprintf(stdout, "%s\n", message.c_str());
7824 }
7825 else if (text.size() > 0)
7826 {
7827 fprintf(stdout, "%s\n", text.c_str());
7828 }
7829 return true;
7830 }
7832 virtual bool parse(Element *elem)
7833 {
7834 if (!parent.getValue(elem, textOpt))
7835 return false;
7836 textOpt = leftJustify(textOpt);
7837 if (!parent.getAttribute(elem, "message", messageOpt))
7838 return false;
7839 return true;
7840 }
7842 private:
7844 String messageOpt;
7845 String textOpt;
7846 };
7850 /**
7851 *
7852 */
7853 class TaskJar : public Task
7854 {
7855 public:
7857 TaskJar(MakeBase &par) : Task(par)
7858 { type = TASK_JAR; name = "jar"; }
7860 virtual ~TaskJar()
7861 {}
7863 virtual bool execute()
7864 {
7865 String command = parent.eval(commandOpt, "jar");
7866 String basedir = parent.eval(basedirOpt, ".");
7867 String destfile = parent.eval(destfileOpt, ".");
7869 String cmd = command;
7870 cmd.append(" -cf ");
7871 cmd.append(destfile);
7872 cmd.append(" -C ");
7873 cmd.append(basedir);
7874 cmd.append(" .");
7876 String execCmd = cmd;
7878 String outString, errString;
7879 bool ret = executeCommand(execCmd.c_str(), "", outString, errString);
7880 if (!ret)
7881 {
7882 error("<jar> command '%s' failed :\n %s",
7883 execCmd.c_str(), errString.c_str());
7884 return false;
7885 }
7886 removeFromStatCache(getNativePath(destfile));
7887 return true;
7888 }
7890 virtual bool parse(Element *elem)
7891 {
7892 if (!parent.getAttribute(elem, "command", commandOpt))
7893 return false;
7894 if (!parent.getAttribute(elem, "basedir", basedirOpt))
7895 return false;
7896 if (!parent.getAttribute(elem, "destfile", destfileOpt))
7897 return false;
7898 if (basedirOpt.size() == 0 || destfileOpt.size() == 0)
7899 {
7900 error("<jar> required both basedir and destfile attributes to be set");
7901 return false;
7902 }
7903 return true;
7904 }
7906 private:
7908 String commandOpt;
7909 String basedirOpt;
7910 String destfileOpt;
7911 };
7914 /**
7915 *
7916 */
7917 class TaskJavac : public Task
7918 {
7919 public:
7921 TaskJavac(MakeBase &par) : Task(par)
7922 {
7923 type = TASK_JAVAC; name = "javac";
7924 }
7926 virtual ~TaskJavac()
7927 {}
7929 virtual bool execute()
7930 {
7931 String command = parent.eval(commandOpt, "javac");
7932 String srcdir = parent.eval(srcdirOpt, ".");
7933 String destdir = parent.eval(destdirOpt, ".");
7934 String target = parent.eval(targetOpt, "");
7936 std::vector<String> fileList;
7937 if (!listFiles(srcdir, "", fileList))
7938 {
7939 return false;
7940 }
7941 String cmd = command;
7942 cmd.append(" -d ");
7943 cmd.append(destdir);
7944 cmd.append(" -classpath ");
7945 cmd.append(destdir);
7946 cmd.append(" -sourcepath ");
7947 cmd.append(srcdir);
7948 cmd.append(" ");
7949 if (target.size()>0)
7950 {
7951 cmd.append(" -target ");
7952 cmd.append(target);
7953 cmd.append(" ");
7954 }
7955 String fname = "javalist.btool";
7956 FILE *f = fopen(fname.c_str(), "w");
7957 int count = 0;
7958 for (unsigned int i=0 ; i<fileList.size() ; i++)
7959 {
7960 String fname = fileList[i];
7961 String srcName = fname;
7962 if (fname.size()<6) //x.java
7963 continue;
7964 if (fname.compare(fname.size()-5, 5, ".java") != 0)
7965 continue;
7966 String baseName = fname.substr(0, fname.size()-5);
7967 String destName = baseName;
7968 destName.append(".class");
7970 String fullSrc = srcdir;
7971 fullSrc.append("/");
7972 fullSrc.append(fname);
7973 String fullDest = destdir;
7974 fullDest.append("/");
7975 fullDest.append(destName);
7976 //trace("fullsrc:%s fulldest:%s", fullSrc.c_str(), fullDest.c_str());
7977 if (!isNewerThan(fullSrc, fullDest))
7978 continue;
7980 count++;
7981 fprintf(f, "%s\n", fullSrc.c_str());
7982 }
7983 fclose(f);
7984 if (!count)
7985 {
7986 taskstatus("nothing to do");
7987 return true;
7988 }
7990 taskstatus("compiling %d files", count);
7992 String execCmd = cmd;
7993 execCmd.append("@");
7994 execCmd.append(fname);
7996 String outString, errString;
7997 bool ret = executeCommand(execCmd.c_str(), "", outString, errString);
7998 if (!ret)
7999 {
8000 error("<javac> command '%s' failed :\n %s",
8001 execCmd.c_str(), errString.c_str());
8002 return false;
8003 }
8004 // TODO:
8005 //removeFromStatCache(getNativePath(........));
8006 return true;
8007 }
8009 virtual bool parse(Element *elem)
8010 {
8011 if (!parent.getAttribute(elem, "command", commandOpt))
8012 return false;
8013 if (!parent.getAttribute(elem, "srcdir", srcdirOpt))
8014 return false;
8015 if (!parent.getAttribute(elem, "destdir", destdirOpt))
8016 return false;
8017 if (srcdirOpt.size() == 0 || destdirOpt.size() == 0)
8018 {
8019 error("<javac> required both srcdir and destdir attributes to be set");
8020 return false;
8021 }
8022 if (!parent.getAttribute(elem, "target", targetOpt))
8023 return false;
8024 return true;
8025 }
8027 private:
8029 String commandOpt;
8030 String srcdirOpt;
8031 String destdirOpt;
8032 String targetOpt;
8034 };
8037 /**
8038 *
8039 */
8040 class TaskLink : public Task
8041 {
8042 public:
8044 TaskLink(MakeBase &par) : Task(par)
8045 {
8046 type = TASK_LINK; name = "link";
8047 }
8049 virtual ~TaskLink()
8050 {}
8052 virtual bool execute()
8053 {
8054 String command = parent.eval(commandOpt, "g++");
8055 String fileName = parent.eval(fileNameOpt, "");
8056 String flags = parent.eval(flagsOpt, "");
8057 String libs = parent.eval(libsOpt, "");
8058 bool doStrip = parent.evalBool(doStripOpt, false);
8059 String symFileName = parent.eval(symFileNameOpt, "");
8060 String stripCommand = parent.eval(stripCommandOpt, "strip");
8061 String objcopyCommand = parent.eval(objcopyCommandOpt, "objcopy");
8063 if (!listFiles(parent, fileSet))
8064 return false;
8065 String fileSetDir = parent.eval(fileSet.getDirectory(), ".");
8066 //trace("%d files in %s", fileSet.size(), fileSetDir.c_str());
8067 bool doit = false;
8068 String fullTarget = parent.resolve(fileName);
8069 String cmd = command;
8070 cmd.append(" -o ");
8071 cmd.append(fullTarget);
8072 cmd.append(" ");
8073 cmd.append(flags);
8074 for (unsigned int i=0 ; i<fileSet.size() ; i++)
8075 {
8076 cmd.append(" ");
8077 String obj;
8078 if (fileSetDir.size()>0)
8079 {
8080 obj.append(fileSetDir);
8081 obj.append("/");
8082 }
8083 obj.append(fileSet[i]);
8084 String fullObj = parent.resolve(obj);
8085 String nativeFullObj = getNativePath(fullObj);
8086 cmd.append(nativeFullObj);
8087 //trace("link: tgt:%s obj:%s", fullTarget.c_str(),
8088 // fullObj.c_str());
8089 if (isNewerThan(fullObj, fullTarget))
8090 doit = true;
8091 }
8092 cmd.append(" ");
8093 cmd.append(libs);
8094 if (!doit)
8095 {
8096 //trace("link not needed");
8097 return true;
8098 }
8099 //trace("LINK cmd:%s", cmd.c_str());
8102 String outbuf, errbuf;
8103 if (!executeCommand(cmd.c_str(), "", outbuf, errbuf))
8104 {
8105 error("LINK problem: %s", errbuf.c_str());
8106 return false;
8107 }
8108 removeFromStatCache(getNativePath(fullTarget));
8110 if (symFileName.size()>0)
8111 {
8112 String symFullName = parent.resolve(symFileName);
8113 cmd = objcopyCommand;
8114 cmd.append(" --only-keep-debug ");
8115 cmd.append(getNativePath(fullTarget));
8116 cmd.append(" ");
8117 cmd.append(getNativePath(symFullName));
8118 if (!executeCommand(cmd, "", outbuf, errbuf))
8119 {
8120 error("<strip> symbol file failed : %s", errbuf.c_str());
8121 return false;
8122 }
8123 removeFromStatCache(getNativePath(symFullName));
8124 }
8126 if (doStrip)
8127 {
8128 cmd = stripCommand;
8129 cmd.append(" ");
8130 cmd.append(getNativePath(fullTarget));
8131 if (!executeCommand(cmd, "", outbuf, errbuf))
8132 {
8133 error("<strip> failed : %s", errbuf.c_str());
8134 return false;
8135 }
8136 removeFromStatCache(getNativePath(fullTarget));
8137 }
8139 return true;
8140 }
8142 virtual bool parse(Element *elem)
8143 {
8144 if (!parent.getAttribute(elem, "command", commandOpt))
8145 return false;
8146 if (!parent.getAttribute(elem, "objcopycommand", objcopyCommandOpt))
8147 return false;
8148 if (!parent.getAttribute(elem, "stripcommand", stripCommandOpt))
8149 return false;
8150 if (!parent.getAttribute(elem, "out", fileNameOpt))
8151 return false;
8152 if (!parent.getAttribute(elem, "strip", doStripOpt))
8153 return false;
8154 if (!parent.getAttribute(elem, "symfile", symFileNameOpt))
8155 return false;
8157 std::vector<Element *> children = elem->getChildren();
8158 for (unsigned int i=0 ; i<children.size() ; i++)
8159 {
8160 Element *child = children[i];
8161 String tagName = child->getName();
8162 if (tagName == "fileset")
8163 {
8164 if (!parseFileSet(child, parent, fileSet))
8165 return false;
8166 }
8167 else if (tagName == "flags")
8168 {
8169 if (!parent.getValue(child, flagsOpt))
8170 return false;
8171 flagsOpt = strip(flagsOpt);
8172 }
8173 else if (tagName == "libs")
8174 {
8175 if (!parent.getValue(child, libsOpt))
8176 return false;
8177 libsOpt = strip(libsOpt);
8178 }
8179 }
8180 return true;
8181 }
8183 private:
8185 FileSet fileSet;
8187 String commandOpt;
8188 String fileNameOpt;
8189 String flagsOpt;
8190 String libsOpt;
8191 String doStripOpt;
8192 String symFileNameOpt;
8193 String stripCommandOpt;
8194 String objcopyCommandOpt;
8196 };
8200 /**
8201 * Create a named file
8202 */
8203 class TaskMakeFile : public Task
8204 {
8205 public:
8207 TaskMakeFile(MakeBase &par) : Task(par)
8208 { type = TASK_MAKEFILE; name = "makefile"; }
8210 virtual ~TaskMakeFile()
8211 {}
8213 virtual bool execute()
8214 {
8215 String fileName = parent.eval(fileNameOpt, "");
8216 bool force = parent.evalBool(forceOpt, false);
8217 String text = parent.eval(textOpt, "");
8219 taskstatus("%s", fileName.c_str());
8220 String fullName = parent.resolve(fileName);
8221 if (!force && !isNewerThan(parent.getURI().getPath(), fullName))
8222 {
8223 taskstatus("skipped");
8224 return true;
8225 }
8226 String fullNative = getNativePath(fullName);
8227 //trace("fullName:%s", fullName.c_str());
8228 FILE *f = fopen(fullNative.c_str(), "w");
8229 if (!f)
8230 {
8231 error("<makefile> could not open %s for writing : %s",
8232 fullName.c_str(), strerror(errno));
8233 return false;
8234 }
8235 for (unsigned int i=0 ; i<text.size() ; i++)
8236 fputc(text[i], f);
8237 fputc('\n', f);
8238 fclose(f);
8239 removeFromStatCache(fullNative);
8240 return true;
8241 }
8243 virtual bool parse(Element *elem)
8244 {
8245 if (!parent.getAttribute(elem, "file", fileNameOpt))
8246 return false;
8247 if (!parent.getAttribute(elem, "force", forceOpt))
8248 return false;
8249 if (fileNameOpt.size() == 0)
8250 {
8251 error("<makefile> requires 'file=\"filename\"' attribute");
8252 return false;
8253 }
8254 if (!parent.getValue(elem, textOpt))
8255 return false;
8256 textOpt = leftJustify(textOpt);
8257 //trace("dirname:%s", dirName.c_str());
8258 return true;
8259 }
8261 private:
8263 String fileNameOpt;
8264 String forceOpt;
8265 String textOpt;
8266 };
8270 /**
8271 * Create a named directory
8272 */
8273 class TaskMkDir : public Task
8274 {
8275 public:
8277 TaskMkDir(MakeBase &par) : Task(par)
8278 { type = TASK_MKDIR; name = "mkdir"; }
8280 virtual ~TaskMkDir()
8281 {}
8283 virtual bool execute()
8284 {
8285 String dirName = parent.eval(dirNameOpt, ".");
8287 taskstatus("%s", dirName.c_str());
8288 String fullDir = parent.resolve(dirName);
8289 //trace("fullDir:%s", fullDir.c_str());
8290 if (!createDirectory(fullDir))
8291 return false;
8292 return true;
8293 }
8295 virtual bool parse(Element *elem)
8296 {
8297 if (!parent.getAttribute(elem, "dir", dirNameOpt))
8298 return false;
8299 if (dirNameOpt.size() == 0)
8300 {
8301 error("<mkdir> requires 'dir=\"dirname\"' attribute");
8302 return false;
8303 }
8304 return true;
8305 }
8307 private:
8309 String dirNameOpt;
8310 };
8314 /**
8315 * Create a named directory
8316 */
8317 class TaskMsgFmt: public Task
8318 {
8319 public:
8321 TaskMsgFmt(MakeBase &par) : Task(par)
8322 { type = TASK_MSGFMT; name = "msgfmt"; }
8324 virtual ~TaskMsgFmt()
8325 {}
8327 virtual bool execute()
8328 {
8329 String command = parent.eval(commandOpt, "msgfmt");
8330 String toDirName = parent.eval(toDirNameOpt, ".");
8331 String outName = parent.eval(outNameOpt, "");
8332 bool owndir = parent.evalBool(owndirOpt, false);
8334 if (!listFiles(parent, fileSet))
8335 return false;
8336 String fileSetDir = fileSet.getDirectory();
8338 //trace("msgfmt: %d", fileSet.size());
8339 for (unsigned int i=0 ; i<fileSet.size() ; i++)
8340 {
8341 String fileName = fileSet[i];
8342 if (getSuffix(fileName) != "po")
8343 continue;
8344 String sourcePath;
8345 if (fileSetDir.size()>0)
8346 {
8347 sourcePath.append(fileSetDir);
8348 sourcePath.append("/");
8349 }
8350 sourcePath.append(fileName);
8351 String fullSource = parent.resolve(sourcePath);
8353 String destPath;
8354 if (toDirName.size()>0)
8355 {
8356 destPath.append(toDirName);
8357 destPath.append("/");
8358 }
8359 if (owndir)
8360 {
8361 String subdir = fileName;
8362 unsigned int pos = subdir.find_last_of('.');
8363 if (pos != subdir.npos)
8364 subdir = subdir.substr(0, pos);
8365 destPath.append(subdir);
8366 destPath.append("/");
8367 }
8368 //Pick the output file name
8369 if (outName.size() > 0)
8370 {
8371 destPath.append(outName);
8372 }
8373 else
8374 {
8375 destPath.append(fileName);
8376 destPath[destPath.size()-2] = 'm';
8377 }
8379 String fullDest = parent.resolve(destPath);
8381 if (!isNewerThan(fullSource, fullDest))
8382 {
8383 //trace("skip %s", fullSource.c_str());
8384 continue;
8385 }
8387 String cmd = command;
8388 cmd.append(" ");
8389 cmd.append(fullSource);
8390 cmd.append(" -o ");
8391 cmd.append(fullDest);
8393 int pos = fullDest.find_last_of('/');
8394 if (pos>0)
8395 {
8396 String fullDestPath = fullDest.substr(0, pos);
8397 if (!createDirectory(fullDestPath))
8398 return false;
8399 }
8403 String outString, errString;
8404 if (!executeCommand(cmd.c_str(), "", outString, errString))
8405 {
8406 error("<msgfmt> problem: %s", errString.c_str());
8407 return false;
8408 }
8409 removeFromStatCache(getNativePath(fullDest));
8410 }
8412 return true;
8413 }
8415 virtual bool parse(Element *elem)
8416 {
8417 if (!parent.getAttribute(elem, "command", commandOpt))
8418 return false;
8419 if (!parent.getAttribute(elem, "todir", toDirNameOpt))
8420 return false;
8421 if (!parent.getAttribute(elem, "out", outNameOpt))
8422 return false;
8423 if (!parent.getAttribute(elem, "owndir", owndirOpt))
8424 return false;
8426 std::vector<Element *> children = elem->getChildren();
8427 for (unsigned int i=0 ; i<children.size() ; i++)
8428 {
8429 Element *child = children[i];
8430 String tagName = child->getName();
8431 if (tagName == "fileset")
8432 {
8433 if (!parseFileSet(child, parent, fileSet))
8434 return false;
8435 }
8436 }
8437 return true;
8438 }
8440 private:
8442 FileSet fileSet;
8444 String commandOpt;
8445 String toDirNameOpt;
8446 String outNameOpt;
8447 String owndirOpt;
8449 };
8453 /**
8454 * Perform a Package-Config query similar to pkg-config
8455 */
8456 class TaskPkgConfig : public Task
8457 {
8458 public:
8460 typedef enum
8461 {
8462 PKG_CONFIG_QUERY_CFLAGS,
8463 PKG_CONFIG_QUERY_LIBS,
8464 PKG_CONFIG_QUERY_ALL
8465 } QueryTypes;
8467 TaskPkgConfig(MakeBase &par) : Task(par)
8468 {
8469 type = TASK_PKG_CONFIG;
8470 name = "pkg-config";
8471 }
8473 virtual ~TaskPkgConfig()
8474 {}
8476 virtual bool execute()
8477 {
8478 String pkgName = parent.eval(pkgNameOpt, "");
8479 String prefix = parent.eval(prefixOpt, "");
8480 String propName = parent.eval(propNameOpt, "");
8481 String pkgConfigPath = parent.eval(pkgConfigPathOpt,"");
8482 String query = parent.eval(queryOpt, "all");
8484 String path = parent.resolve(pkgConfigPath);
8485 PkgConfig pkgconfig;
8486 pkgconfig.setPath(path);
8487 pkgconfig.setPrefix(prefix);
8488 if (!pkgconfig.query(pkgName))
8489 {
8490 error("<pkg-config> query failed for '%s", name.c_str());
8491 return false;
8492 }
8494 String val = "";
8495 if (query == "cflags")
8496 val = pkgconfig.getCflags();
8497 else if (query == "libs")
8498 val =pkgconfig.getLibs();
8499 else if (query == "all")
8500 val = pkgconfig.getAll();
8501 else
8502 {
8503 error("<pkg-config> unhandled query : %s", query.c_str());
8504 return false;
8505 }
8506 taskstatus("property %s = '%s'", propName.c_str(), val.c_str());
8507 parent.setProperty(propName, val);
8508 return true;
8509 }
8511 virtual bool parse(Element *elem)
8512 {
8513 //# NAME
8514 if (!parent.getAttribute(elem, "name", pkgNameOpt))
8515 return false;
8516 if (pkgNameOpt.size()==0)
8517 {
8518 error("<pkg-config> requires 'name=\"package\"' attribute");
8519 return false;
8520 }
8522 //# PROPERTY
8523 if (!parent.getAttribute(elem, "property", propNameOpt))
8524 return false;
8525 if (propNameOpt.size()==0)
8526 {
8527 error("<pkg-config> requires 'property=\"name\"' attribute");
8528 return false;
8529 }
8530 //# PATH
8531 if (!parent.getAttribute(elem, "path", pkgConfigPathOpt))
8532 return false;
8533 //# PREFIX
8534 if (!parent.getAttribute(elem, "prefix", prefixOpt))
8535 return false;
8536 //# QUERY
8537 if (!parent.getAttribute(elem, "query", queryOpt))
8538 return false;
8540 return true;
8541 }
8543 private:
8545 String queryOpt;
8546 String pkgNameOpt;
8547 String prefixOpt;
8548 String propNameOpt;
8549 String pkgConfigPathOpt;
8551 };
8558 /**
8559 * Process an archive to allow random access
8560 */
8561 class TaskRanlib : public Task
8562 {
8563 public:
8565 TaskRanlib(MakeBase &par) : Task(par)
8566 { type = TASK_RANLIB; name = "ranlib"; }
8568 virtual ~TaskRanlib()
8569 {}
8571 virtual bool execute()
8572 {
8573 String fileName = parent.eval(fileNameOpt, "");
8574 String command = parent.eval(commandOpt, "ranlib");
8576 String fullName = parent.resolve(fileName);
8577 //trace("fullDir:%s", fullDir.c_str());
8578 String cmd = command;
8579 cmd.append(" ");
8580 cmd.append(fullName);
8581 String outbuf, errbuf;
8582 if (!executeCommand(cmd, "", outbuf, errbuf))
8583 return false;
8584 // TODO:
8585 //removeFromStatCache(getNativePath(fullDest));
8586 return true;
8587 }
8589 virtual bool parse(Element *elem)
8590 {
8591 if (!parent.getAttribute(elem, "command", commandOpt))
8592 return false;
8593 if (!parent.getAttribute(elem, "file", fileNameOpt))
8594 return false;
8595 if (fileNameOpt.size() == 0)
8596 {
8597 error("<ranlib> requires 'file=\"fileNname\"' attribute");
8598 return false;
8599 }
8600 return true;
8601 }
8603 private:
8605 String fileNameOpt;
8606 String commandOpt;
8607 };
8611 /**
8612 * Compile a resource file into a binary object
8613 */
8614 class TaskRC : public Task
8615 {
8616 public:
8618 TaskRC(MakeBase &par) : Task(par)
8619 { type = TASK_RC; name = "rc"; }
8621 virtual ~TaskRC()
8622 {}
8624 virtual bool execute()
8625 {
8626 String command = parent.eval(commandOpt, "windres");
8627 String flags = parent.eval(flagsOpt, "");
8628 String fileName = parent.eval(fileNameOpt, "");
8629 String outName = parent.eval(outNameOpt, "");
8631 String fullFile = parent.resolve(fileName);
8632 String fullOut = parent.resolve(outName);
8633 if (!isNewerThan(fullFile, fullOut))
8634 return true;
8635 String cmd = command;
8636 cmd.append(" -o ");
8637 cmd.append(fullOut);
8638 cmd.append(" ");
8639 cmd.append(flags);
8640 cmd.append(" ");
8641 cmd.append(fullFile);
8643 String outString, errString;
8644 if (!executeCommand(cmd.c_str(), "", outString, errString))
8645 {
8646 error("RC problem: %s", errString.c_str());
8647 return false;
8648 }
8649 removeFromStatCache(getNativePath(fullOut));
8650 return true;
8651 }
8653 virtual bool parse(Element *elem)
8654 {
8655 if (!parent.getAttribute(elem, "command", commandOpt))
8656 return false;
8657 if (!parent.getAttribute(elem, "file", fileNameOpt))
8658 return false;
8659 if (!parent.getAttribute(elem, "out", outNameOpt))
8660 return false;
8661 std::vector<Element *> children = elem->getChildren();
8662 for (unsigned int i=0 ; i<children.size() ; i++)
8663 {
8664 Element *child = children[i];
8665 String tagName = child->getName();
8666 if (tagName == "flags")
8667 {
8668 if (!parent.getValue(child, flagsOpt))
8669 return false;
8670 }
8671 }
8672 return true;
8673 }
8675 private:
8677 String commandOpt;
8678 String flagsOpt;
8679 String fileNameOpt;
8680 String outNameOpt;
8682 };
8686 /**
8687 * Collect .o's into a .so or DLL
8688 */
8689 class TaskSharedLib : public Task
8690 {
8691 public:
8693 TaskSharedLib(MakeBase &par) : Task(par)
8694 { type = TASK_SHAREDLIB; name = "dll"; }
8696 virtual ~TaskSharedLib()
8697 {}
8699 virtual bool execute()
8700 {
8701 String command = parent.eval(commandOpt, "dllwrap");
8702 String fileName = parent.eval(fileNameOpt, "");
8703 String defFileName = parent.eval(defFileNameOpt, "");
8704 String impFileName = parent.eval(impFileNameOpt, "");
8705 String libs = parent.eval(libsOpt, "");
8707 //trace("###########HERE %d", fileSet.size());
8708 bool doit = false;
8710 String fullOut = parent.resolve(fileName);
8711 //trace("ar fullout: %s", fullOut.c_str());
8713 if (!listFiles(parent, fileSet))
8714 return false;
8715 String fileSetDir = parent.eval(fileSet.getDirectory(), ".");
8717 for (unsigned int i=0 ; i<fileSet.size() ; i++)
8718 {
8719 String fname;
8720 if (fileSetDir.size()>0)
8721 {
8722 fname.append(fileSetDir);
8723 fname.append("/");
8724 }
8725 fname.append(fileSet[i]);
8726 String fullName = parent.resolve(fname);
8727 //trace("ar : %s/%s", fullOut.c_str(), fullName.c_str());
8728 if (isNewerThan(fullName, fullOut))
8729 doit = true;
8730 }
8731 //trace("Needs it:%d", doit);
8732 if (!doit)
8733 {
8734 return true;
8735 }
8737 String cmd = "dllwrap";
8738 cmd.append(" -o ");
8739 cmd.append(fullOut);
8740 if (defFileName.size()>0)
8741 {
8742 cmd.append(" --def ");
8743 cmd.append(defFileName);
8744 cmd.append(" ");
8745 }
8746 if (impFileName.size()>0)
8747 {
8748 cmd.append(" --implib ");
8749 cmd.append(impFileName);
8750 cmd.append(" ");
8751 }
8752 for (unsigned int i=0 ; i<fileSet.size() ; i++)
8753 {
8754 String fname;
8755 if (fileSetDir.size()>0)
8756 {
8757 fname.append(fileSetDir);
8758 fname.append("/");
8759 }
8760 fname.append(fileSet[i]);
8761 String fullName = parent.resolve(fname);
8763 cmd.append(" ");
8764 cmd.append(fullName);
8765 }
8766 cmd.append(" ");
8767 cmd.append(libs);
8769 String outString, errString;
8770 if (!executeCommand(cmd.c_str(), "", outString, errString))
8771 {
8772 error("<sharedlib> problem: %s", errString.c_str());
8773 return false;
8774 }
8775 removeFromStatCache(getNativePath(fullOut));
8776 return true;
8777 }
8779 virtual bool parse(Element *elem)
8780 {
8781 if (!parent.getAttribute(elem, "command", commandOpt))
8782 return false;
8783 if (!parent.getAttribute(elem, "file", fileNameOpt))
8784 return false;
8785 if (!parent.getAttribute(elem, "import", impFileNameOpt))
8786 return false;
8787 if (!parent.getAttribute(elem, "def", defFileNameOpt))
8788 return false;
8790 std::vector<Element *> children = elem->getChildren();
8791 for (unsigned int i=0 ; i<children.size() ; i++)
8792 {
8793 Element *child = children[i];
8794 String tagName = child->getName();
8795 if (tagName == "fileset")
8796 {
8797 if (!parseFileSet(child, parent, fileSet))
8798 return false;
8799 }
8800 else if (tagName == "libs")
8801 {
8802 if (!parent.getValue(child, libsOpt))
8803 return false;
8804 libsOpt = strip(libsOpt);
8805 }
8806 }
8807 return true;
8808 }
8810 private:
8812 FileSet fileSet;
8814 String commandOpt;
8815 String fileNameOpt;
8816 String defFileNameOpt;
8817 String impFileNameOpt;
8818 String libsOpt;
8820 };
8824 /**
8825 * Run the "ar" command to archive .o's into a .a
8826 */
8827 class TaskStaticLib : public Task
8828 {
8829 public:
8831 TaskStaticLib(MakeBase &par) : Task(par)
8832 { type = TASK_STATICLIB; name = "staticlib"; }
8834 virtual ~TaskStaticLib()
8835 {}
8837 virtual bool execute()
8838 {
8839 String command = parent.eval(commandOpt, "ar crv");
8840 String fileName = parent.eval(fileNameOpt, "");
8842 bool doit = false;
8844 String fullOut = parent.resolve(fileName);
8845 //trace("ar fullout: %s", fullOut.c_str());
8847 if (!listFiles(parent, fileSet))
8848 return false;
8849 String fileSetDir = parent.eval(fileSet.getDirectory(), ".");
8850 //trace("###########HERE %s", fileSetDir.c_str());
8852 for (unsigned int i=0 ; i<fileSet.size() ; i++)
8853 {
8854 String fname;
8855 if (fileSetDir.size()>0)
8856 {
8857 fname.append(fileSetDir);
8858 fname.append("/");
8859 }
8860 fname.append(fileSet[i]);
8861 String fullName = parent.resolve(fname);
8862 //trace("ar : %s/%s", fullOut.c_str(), fullName.c_str());
8863 if (isNewerThan(fullName, fullOut))
8864 doit = true;
8865 }
8866 //trace("Needs it:%d", doit);
8867 if (!doit)
8868 {
8869 return true;
8870 }
8872 String cmd = command;
8873 cmd.append(" ");
8874 cmd.append(fullOut);
8875 for (unsigned int i=0 ; i<fileSet.size() ; i++)
8876 {
8877 String fname;
8878 if (fileSetDir.size()>0)
8879 {
8880 fname.append(fileSetDir);
8881 fname.append("/");
8882 }
8883 fname.append(fileSet[i]);
8884 String fullName = parent.resolve(fname);
8886 cmd.append(" ");
8887 cmd.append(fullName);
8888 }
8890 String outString, errString;
8891 if (!executeCommand(cmd.c_str(), "", outString, errString))
8892 {
8893 error("<staticlib> problem: %s", errString.c_str());
8894 return false;
8895 }
8896 removeFromStatCache(getNativePath(fullOut));
8897 return true;
8898 }
8901 virtual bool parse(Element *elem)
8902 {
8903 if (!parent.getAttribute(elem, "command", commandOpt))
8904 return false;
8905 if (!parent.getAttribute(elem, "file", fileNameOpt))
8906 return false;
8908 std::vector<Element *> children = elem->getChildren();
8909 for (unsigned int i=0 ; i<children.size() ; i++)
8910 {
8911 Element *child = children[i];
8912 String tagName = child->getName();
8913 if (tagName == "fileset")
8914 {
8915 if (!parseFileSet(child, parent, fileSet))
8916 return false;
8917 }
8918 }
8919 return true;
8920 }
8922 private:
8924 FileSet fileSet;
8926 String commandOpt;
8927 String fileNameOpt;
8929 };
8934 /**
8935 * Strip an executable
8936 */
8937 class TaskStrip : public Task
8938 {
8939 public:
8941 TaskStrip(MakeBase &par) : Task(par)
8942 { type = TASK_STRIP; name = "strip"; }
8944 virtual ~TaskStrip()
8945 {}
8947 virtual bool execute()
8948 {
8949 String command = parent.eval(commandOpt, "strip");
8950 String fileName = parent.eval(fileNameOpt, "");
8951 String symFileName = parent.eval(symFileNameOpt, "");
8953 String fullName = parent.resolve(fileName);
8954 //trace("fullDir:%s", fullDir.c_str());
8955 String cmd;
8956 String outbuf, errbuf;
8958 if (symFileName.size()>0)
8959 {
8960 String symFullName = parent.resolve(symFileName);
8961 cmd = "objcopy --only-keep-debug ";
8962 cmd.append(getNativePath(fullName));
8963 cmd.append(" ");
8964 cmd.append(getNativePath(symFullName));
8965 if (!executeCommand(cmd, "", outbuf, errbuf))
8966 {
8967 error("<strip> symbol file failed : %s", errbuf.c_str());
8968 return false;
8969 }
8970 }
8972 cmd = command;
8973 cmd.append(getNativePath(fullName));
8974 if (!executeCommand(cmd, "", outbuf, errbuf))
8975 {
8976 error("<strip> failed : %s", errbuf.c_str());
8977 return false;
8978 }
8979 removeFromStatCache(getNativePath(fullName));
8980 return true;
8981 }
8983 virtual bool parse(Element *elem)
8984 {
8985 if (!parent.getAttribute(elem, "command", commandOpt))
8986 return false;
8987 if (!parent.getAttribute(elem, "file", fileNameOpt))
8988 return false;
8989 if (!parent.getAttribute(elem, "symfile", symFileNameOpt))
8990 return false;
8991 if (fileNameOpt.size() == 0)
8992 {
8993 error("<strip> requires 'file=\"fileName\"' attribute");
8994 return false;
8995 }
8996 return true;
8997 }
8999 private:
9001 String commandOpt;
9002 String fileNameOpt;
9003 String symFileNameOpt;
9004 };
9007 /**
9008 *
9009 */
9010 class TaskTouch : public Task
9011 {
9012 public:
9014 TaskTouch(MakeBase &par) : Task(par)
9015 { type = TASK_TOUCH; name = "touch"; }
9017 virtual ~TaskTouch()
9018 {}
9020 virtual bool execute()
9021 {
9022 String fileName = parent.eval(fileNameOpt, "");
9024 String fullName = parent.resolve(fileName);
9025 String nativeFile = getNativePath(fullName);
9026 if (!isRegularFile(fullName) && !isDirectory(fullName))
9027 {
9028 // S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH
9029 int ret = creat(nativeFile.c_str(), 0666);
9030 if (ret != 0)
9031 {
9032 error("<touch> could not create '%s' : %s",
9033 nativeFile.c_str(), strerror(ret));
9034 return false;
9035 }
9036 return true;
9037 }
9038 int ret = utime(nativeFile.c_str(), (struct utimbuf *)0);
9039 if (ret != 0)
9040 {
9041 error("<touch> could not update the modification time for '%s' : %s",
9042 nativeFile.c_str(), strerror(ret));
9043 return false;
9044 }
9045 removeFromStatCache(nativeFile);
9046 return true;
9047 }
9049 virtual bool parse(Element *elem)
9050 {
9051 //trace("touch parse");
9052 if (!parent.getAttribute(elem, "file", fileNameOpt))
9053 return false;
9054 if (fileNameOpt.size() == 0)
9055 {
9056 error("<touch> requires 'file=\"fileName\"' attribute");
9057 return false;
9058 }
9059 return true;
9060 }
9062 String fileNameOpt;
9063 };
9066 /**
9067 *
9068 */
9069 class TaskTstamp : public Task
9070 {
9071 public:
9073 TaskTstamp(MakeBase &par) : Task(par)
9074 { type = TASK_TSTAMP; name = "tstamp"; }
9076 virtual ~TaskTstamp()
9077 {}
9079 virtual bool execute()
9080 {
9081 return true;
9082 }
9084 virtual bool parse(Element *elem)
9085 {
9086 //trace("tstamp parse");
9087 return true;
9088 }
9089 };
9093 /**
9094 *
9095 */
9096 Task *Task::createTask(Element *elem, int lineNr)
9097 {
9098 String tagName = elem->getName();
9099 //trace("task:%s", tagName.c_str());
9100 Task *task = NULL;
9101 if (tagName == "cc")
9102 task = new TaskCC(parent);
9103 else if (tagName == "copy")
9104 task = new TaskCopy(parent);
9105 else if (tagName == "cxxtestpart")
9106 task = new TaskCxxTestPart(parent);
9107 else if (tagName == "cxxtestroot")
9108 task = new TaskCxxTestRoot(parent);
9109 else if (tagName == "cxxtestrun")
9110 task = new TaskCxxTestRun(parent);
9111 else if (tagName == "delete")
9112 task = new TaskDelete(parent);
9113 else if (tagName == "echo")
9114 task = new TaskEcho(parent);
9115 else if (tagName == "jar")
9116 task = new TaskJar(parent);
9117 else if (tagName == "javac")
9118 task = new TaskJavac(parent);
9119 else if (tagName == "link")
9120 task = new TaskLink(parent);
9121 else if (tagName == "makefile")
9122 task = new TaskMakeFile(parent);
9123 else if (tagName == "mkdir")
9124 task = new TaskMkDir(parent);
9125 else if (tagName == "msgfmt")
9126 task = new TaskMsgFmt(parent);
9127 else if (tagName == "pkg-config")
9128 task = new TaskPkgConfig(parent);
9129 else if (tagName == "ranlib")
9130 task = new TaskRanlib(parent);
9131 else if (tagName == "rc")
9132 task = new TaskRC(parent);
9133 else if (tagName == "sharedlib")
9134 task = new TaskSharedLib(parent);
9135 else if (tagName == "staticlib")
9136 task = new TaskStaticLib(parent);
9137 else if (tagName == "strip")
9138 task = new TaskStrip(parent);
9139 else if (tagName == "touch")
9140 task = new TaskTouch(parent);
9141 else if (tagName == "tstamp")
9142 task = new TaskTstamp(parent);
9143 else
9144 {
9145 error("Unknown task '%s'", tagName.c_str());
9146 return NULL;
9147 }
9149 task->setLine(lineNr);
9151 if (!task->parse(elem))
9152 {
9153 delete task;
9154 return NULL;
9155 }
9156 return task;
9157 }
9161 //########################################################################
9162 //# T A R G E T
9163 //########################################################################
9165 /**
9166 *
9167 */
9168 class Target : public MakeBase
9169 {
9171 public:
9173 /**
9174 *
9175 */
9176 Target(Make &par) : parent(par)
9177 { init(); }
9179 /**
9180 *
9181 */
9182 Target(const Target &other) : parent(other.parent)
9183 { init(); assign(other); }
9185 /**
9186 *
9187 */
9188 Target &operator=(const Target &other)
9189 { init(); assign(other); return *this; }
9191 /**
9192 *
9193 */
9194 virtual ~Target()
9195 { cleanup() ; }
9198 /**
9199 *
9200 */
9201 virtual Make &getParent()
9202 { return parent; }
9204 /**
9205 *
9206 */
9207 virtual String getName()
9208 { return name; }
9210 /**
9211 *
9212 */
9213 virtual void setName(const String &val)
9214 { name = val; }
9216 /**
9217 *
9218 */
9219 virtual String getDescription()
9220 { return description; }
9222 /**
9223 *
9224 */
9225 virtual void setDescription(const String &val)
9226 { description = val; }
9228 /**
9229 *
9230 */
9231 virtual void addDependency(const String &val)
9232 { deps.push_back(val); }
9234 /**
9235 *
9236 */
9237 virtual void parseDependencies(const String &val)
9238 { deps = tokenize(val, ", "); }
9240 /**
9241 *
9242 */
9243 virtual std::vector<String> &getDependencies()
9244 { return deps; }
9246 /**
9247 *
9248 */
9249 virtual String getIf()
9250 { return ifVar; }
9252 /**
9253 *
9254 */
9255 virtual void setIf(const String &val)
9256 { ifVar = val; }
9258 /**
9259 *
9260 */
9261 virtual String getUnless()
9262 { return unlessVar; }
9264 /**
9265 *
9266 */
9267 virtual void setUnless(const String &val)
9268 { unlessVar = val; }
9270 /**
9271 *
9272 */
9273 virtual void addTask(Task *val)
9274 { tasks.push_back(val); }
9276 /**
9277 *
9278 */
9279 virtual std::vector<Task *> &getTasks()
9280 { return tasks; }
9282 private:
9284 void init()
9285 {
9286 }
9288 void cleanup()
9289 {
9290 tasks.clear();
9291 }
9293 void assign(const Target &other)
9294 {
9295 //parent = other.parent;
9296 name = other.name;
9297 description = other.description;
9298 ifVar = other.ifVar;
9299 unlessVar = other.unlessVar;
9300 deps = other.deps;
9301 tasks = other.tasks;
9302 }
9304 Make &parent;
9306 String name;
9308 String description;
9310 String ifVar;
9312 String unlessVar;
9314 std::vector<String> deps;
9316 std::vector<Task *> tasks;
9318 };
9327 //########################################################################
9328 //# M A K E
9329 //########################################################################
9332 /**
9333 *
9334 */
9335 class Make : public MakeBase
9336 {
9338 public:
9340 /**
9341 *
9342 */
9343 Make()
9344 { init(); }
9346 /**
9347 *
9348 */
9349 Make(const Make &other)
9350 { assign(other); }
9352 /**
9353 *
9354 */
9355 Make &operator=(const Make &other)
9356 { assign(other); return *this; }
9358 /**
9359 *
9360 */
9361 virtual ~Make()
9362 { cleanup(); }
9364 /**
9365 *
9366 */
9367 virtual std::map<String, Target> &getTargets()
9368 { return targets; }
9371 /**
9372 *
9373 */
9374 virtual String version()
9375 { return BUILDTOOL_VERSION; }
9377 /**
9378 * Overload a <property>
9379 */
9380 virtual bool specifyProperty(const String &name,
9381 const String &value);
9383 /**
9384 *
9385 */
9386 virtual bool run();
9388 /**
9389 *
9390 */
9391 virtual bool run(const String &target);
9395 private:
9397 /**
9398 *
9399 */
9400 void init();
9402 /**
9403 *
9404 */
9405 void cleanup();
9407 /**
9408 *
9409 */
9410 void assign(const Make &other);
9412 /**
9413 *
9414 */
9415 bool executeTask(Task &task);
9418 /**
9419 *
9420 */
9421 bool executeTarget(Target &target,
9422 std::set<String> &targetsCompleted);
9425 /**
9426 *
9427 */
9428 bool execute();
9430 /**
9431 *
9432 */
9433 bool checkTargetDependencies(Target &prop,
9434 std::vector<String> &depList);
9436 /**
9437 *
9438 */
9439 bool parsePropertyFile(const String &fileName,
9440 const String &prefix);
9442 /**
9443 *
9444 */
9445 bool parseProperty(Element *elem);
9447 /**
9448 *
9449 */
9450 bool parseFile();
9452 /**
9453 *
9454 */
9455 std::vector<String> glob(const String &pattern);
9458 //###############
9459 //# Fields
9460 //###############
9462 String projectName;
9464 String currentTarget;
9466 String defaultTarget;
9468 String specifiedTarget;
9470 String baseDir;
9472 String description;
9474 //std::vector<Property> properties;
9476 std::map<String, Target> targets;
9478 std::vector<Task *> allTasks;
9480 std::map<String, String> specifiedProperties;
9482 };
9485 //########################################################################
9486 //# C L A S S M A I N T E N A N C E
9487 //########################################################################
9489 /**
9490 *
9491 */
9492 void Make::init()
9493 {
9494 uri = "build.xml";
9495 projectName = "";
9496 currentTarget = "";
9497 defaultTarget = "";
9498 specifiedTarget = "";
9499 baseDir = "";
9500 description = "";
9501 envPrefix = "env.";
9502 pcPrefix = "pc.";
9503 pccPrefix = "pcc.";
9504 pclPrefix = "pcl.";
9505 svnPrefix = "svn.";
9506 properties.clear();
9507 for (unsigned int i = 0 ; i < allTasks.size() ; i++)
9508 delete allTasks[i];
9509 allTasks.clear();
9510 }
9514 /**
9515 *
9516 */
9517 void Make::cleanup()
9518 {
9519 for (unsigned int i = 0 ; i < allTasks.size() ; i++)
9520 delete allTasks[i];
9521 allTasks.clear();
9522 }
9526 /**
9527 *
9528 */
9529 void Make::assign(const Make &other)
9530 {
9531 uri = other.uri;
9532 projectName = other.projectName;
9533 currentTarget = other.currentTarget;
9534 defaultTarget = other.defaultTarget;
9535 specifiedTarget = other.specifiedTarget;
9536 baseDir = other.baseDir;
9537 description = other.description;
9538 properties = other.properties;
9539 }
9543 //########################################################################
9544 //# U T I L I T Y T A S K S
9545 //########################################################################
9547 /**
9548 * Perform a file globbing
9549 */
9550 std::vector<String> Make::glob(const String &pattern)
9551 {
9552 std::vector<String> res;
9553 return res;
9554 }
9557 //########################################################################
9558 //# P U B L I C A P I
9559 //########################################################################
9563 /**
9564 *
9565 */
9566 bool Make::executeTarget(Target &target,
9567 std::set<String> &targetsCompleted)
9568 {
9570 String name = target.getName();
9572 //First get any dependencies for this target
9573 std::vector<String> deps = target.getDependencies();
9574 for (unsigned int i=0 ; i<deps.size() ; i++)
9575 {
9576 String dep = deps[i];
9577 //Did we do it already? Skip
9578 if (targetsCompleted.find(dep)!=targetsCompleted.end())
9579 continue;
9581 std::map<String, Target> &tgts =
9582 target.getParent().getTargets();
9583 std::map<String, Target>::iterator iter =
9584 tgts.find(dep);
9585 if (iter == tgts.end())
9586 {
9587 error("Target '%s' dependency '%s' not found",
9588 name.c_str(), dep.c_str());
9589 return false;
9590 }
9591 Target depTarget = iter->second;
9592 if (!executeTarget(depTarget, targetsCompleted))
9593 {
9594 return false;
9595 }
9596 }
9598 status("##### Target : %s\n##### %s", name.c_str(),
9599 target.getDescription().c_str());
9601 //Now let's do the tasks
9602 std::vector<Task *> &tasks = target.getTasks();
9603 for (unsigned int i=0 ; i<tasks.size() ; i++)
9604 {
9605 Task *task = tasks[i];
9606 status("--- %s / %s", name.c_str(), task->getName().c_str());
9607 if (!task->execute())
9608 {
9609 return false;
9610 }
9611 }
9613 targetsCompleted.insert(name);
9615 return true;
9616 }
9620 /**
9621 * Main execute() method. Start here and work
9622 * up the dependency tree
9623 */
9624 bool Make::execute()
9625 {
9626 status("######## EXECUTE");
9628 //Determine initial target
9629 if (specifiedTarget.size()>0)
9630 {
9631 currentTarget = specifiedTarget;
9632 }
9633 else if (defaultTarget.size()>0)
9634 {
9635 currentTarget = defaultTarget;
9636 }
9637 else
9638 {
9639 error("execute: no specified or default target requested");
9640 return false;
9641 }
9643 std::map<String, Target>::iterator iter =
9644 targets.find(currentTarget);
9645 if (iter == targets.end())
9646 {
9647 error("Initial target '%s' not found",
9648 currentTarget.c_str());
9649 return false;
9650 }
9652 //Now run
9653 Target target = iter->second;
9654 std::set<String> targetsCompleted;
9655 if (!executeTarget(target, targetsCompleted))
9656 {
9657 return false;
9658 }
9660 status("######## EXECUTE COMPLETE");
9661 return true;
9662 }
9667 /**
9668 *
9669 */
9670 bool Make::checkTargetDependencies(Target &target,
9671 std::vector<String> &depList)
9672 {
9673 String tgtName = target.getName().c_str();
9674 depList.push_back(tgtName);
9676 std::vector<String> deps = target.getDependencies();
9677 for (unsigned int i=0 ; i<deps.size() ; i++)
9678 {
9679 String dep = deps[i];
9680 //First thing entered was the starting Target
9681 if (dep == depList[0])
9682 {
9683 error("Circular dependency '%s' found at '%s'",
9684 dep.c_str(), tgtName.c_str());
9685 std::vector<String>::iterator diter;
9686 for (diter=depList.begin() ; diter!=depList.end() ; diter++)
9687 {
9688 error(" %s", diter->c_str());
9689 }
9690 return false;
9691 }
9693 std::map<String, Target> &tgts =
9694 target.getParent().getTargets();
9695 std::map<String, Target>::iterator titer = tgts.find(dep);
9696 if (titer == tgts.end())
9697 {
9698 error("Target '%s' dependency '%s' not found",
9699 tgtName.c_str(), dep.c_str());
9700 return false;
9701 }
9702 if (!checkTargetDependencies(titer->second, depList))
9703 {
9704 return false;
9705 }
9706 }
9707 return true;
9708 }
9714 static int getword(int pos, const String &inbuf, String &result)
9715 {
9716 int p = pos;
9717 int len = (int)inbuf.size();
9718 String val;
9719 while (p < len)
9720 {
9721 char ch = inbuf[p];
9722 if (!isalnum(ch) && ch!='.' && ch!='_')
9723 break;
9724 val.push_back(ch);
9725 p++;
9726 }
9727 result = val;
9728 return p;
9729 }
9734 /**
9735 *
9736 */
9737 bool Make::parsePropertyFile(const String &fileName,
9738 const String &prefix)
9739 {
9740 FILE *f = fopen(fileName.c_str(), "r");
9741 if (!f)
9742 {
9743 error("could not open property file %s", fileName.c_str());
9744 return false;
9745 }
9746 int linenr = 0;
9747 while (!feof(f))
9748 {
9749 char buf[256];
9750 if (!fgets(buf, 255, f))
9751 break;
9752 linenr++;
9753 String s = buf;
9754 s = trim(s);
9755 int len = s.size();
9756 if (len == 0)
9757 continue;
9758 if (s[0] == '#')
9759 continue;
9760 String key;
9761 String val;
9762 int p = 0;
9763 int p2 = getword(p, s, key);
9764 if (p2 <= p)
9765 {
9766 error("property file %s, line %d: expected keyword",
9767 fileName.c_str(), linenr);
9768 return false;
9769 }
9770 if (prefix.size() > 0)
9771 {
9772 key.insert(0, prefix);
9773 }
9775 //skip whitespace
9776 for (p=p2 ; p<len ; p++)
9777 if (!isspace(s[p]))
9778 break;
9780 if (p>=len || s[p]!='=')
9781 {
9782 error("property file %s, line %d: expected '='",
9783 fileName.c_str(), linenr);
9784 return false;
9785 }
9786 p++;
9788 //skip whitespace
9789 for ( ; p<len ; p++)
9790 if (!isspace(s[p]))
9791 break;
9793 /* This way expects a word after the =
9794 p2 = getword(p, s, val);
9795 if (p2 <= p)
9796 {
9797 error("property file %s, line %d: expected value",
9798 fileName.c_str(), linenr);
9799 return false;
9800 }
9801 */
9802 // This way gets the rest of the line after the =
9803 if (p>=len)
9804 {
9805 error("property file %s, line %d: expected value",
9806 fileName.c_str(), linenr);
9807 return false;
9808 }
9809 val = s.substr(p);
9810 if (key.size()==0)
9811 continue;
9812 //allow property to be set, even if val=""
9814 //trace("key:'%s' val:'%s'", key.c_str(), val.c_str());
9815 //See if we wanted to overload this property
9816 std::map<String, String>::iterator iter =
9817 specifiedProperties.find(key);
9818 if (iter!=specifiedProperties.end())
9819 {
9820 val = iter->second;
9821 status("overloading property '%s' = '%s'",
9822 key.c_str(), val.c_str());
9823 }
9824 properties[key] = val;
9825 }
9826 fclose(f);
9827 return true;
9828 }
9833 /**
9834 *
9835 */
9836 bool Make::parseProperty(Element *elem)
9837 {
9838 std::vector<Attribute> &attrs = elem->getAttributes();
9839 for (unsigned int i=0 ; i<attrs.size() ; i++)
9840 {
9841 String attrName = attrs[i].getName();
9842 String attrVal = attrs[i].getValue();
9844 if (attrName == "name")
9845 {
9846 String val;
9847 if (!getAttribute(elem, "value", val))
9848 return false;
9849 if (val.size() > 0)
9850 {
9851 properties[attrVal] = val;
9852 }
9853 else
9854 {
9855 if (!getAttribute(elem, "location", val))
9856 return false;
9857 //let the property exist, even if not defined
9858 properties[attrVal] = val;
9859 }
9860 //See if we wanted to overload this property
9861 std::map<String, String>::iterator iter =
9862 specifiedProperties.find(attrVal);
9863 if (iter != specifiedProperties.end())
9864 {
9865 val = iter->second;
9866 status("overloading property '%s' = '%s'",
9867 attrVal.c_str(), val.c_str());
9868 properties[attrVal] = val;
9869 }
9870 }
9871 else if (attrName == "file")
9872 {
9873 String prefix;
9874 if (!getAttribute(elem, "prefix", prefix))
9875 return false;
9876 if (prefix.size() > 0)
9877 {
9878 if (prefix[prefix.size()-1] != '.')
9879 prefix.push_back('.');
9880 }
9881 if (!parsePropertyFile(attrName, prefix))
9882 return false;
9883 }
9884 else if (attrName == "environment")
9885 {
9886 if (attrVal.find('.') != attrVal.npos)
9887 {
9888 error("environment prefix cannot have a '.' in it");
9889 return false;
9890 }
9891 envPrefix = attrVal;
9892 envPrefix.push_back('.');
9893 }
9894 else if (attrName == "pkg-config")
9895 {
9896 if (attrVal.find('.') != attrVal.npos)
9897 {
9898 error("pkg-config prefix cannot have a '.' in it");
9899 return false;
9900 }
9901 pcPrefix = attrVal;
9902 pcPrefix.push_back('.');
9903 }
9904 else if (attrName == "pkg-config-cflags")
9905 {
9906 if (attrVal.find('.') != attrVal.npos)
9907 {
9908 error("pkg-config-cflags prefix cannot have a '.' in it");
9909 return false;
9910 }
9911 pccPrefix = attrVal;
9912 pccPrefix.push_back('.');
9913 }
9914 else if (attrName == "pkg-config-libs")
9915 {
9916 if (attrVal.find('.') != attrVal.npos)
9917 {
9918 error("pkg-config-libs prefix cannot have a '.' in it");
9919 return false;
9920 }
9921 pclPrefix = attrVal;
9922 pclPrefix.push_back('.');
9923 }
9924 else if (attrName == "subversion")
9925 {
9926 if (attrVal.find('.') != attrVal.npos)
9927 {
9928 error("subversion prefix cannot have a '.' in it");
9929 return false;
9930 }
9931 svnPrefix = attrVal;
9932 svnPrefix.push_back('.');
9933 }
9934 }
9936 return true;
9937 }
9942 /**
9943 *
9944 */
9945 bool Make::parseFile()
9946 {
9947 status("######## PARSE : %s", uri.getPath().c_str());
9949 setLine(0);
9951 Parser parser;
9952 Element *root = parser.parseFile(uri.getNativePath());
9953 if (!root)
9954 {
9955 error("Could not open %s for reading",
9956 uri.getNativePath().c_str());
9957 return false;
9958 }
9960 setLine(root->getLine());
9962 if (root->getChildren().size()==0 ||
9963 root->getChildren()[0]->getName()!="project")
9964 {
9965 error("Main xml element should be <project>");
9966 delete root;
9967 return false;
9968 }
9970 //########## Project attributes
9971 Element *project = root->getChildren()[0];
9972 String s = project->getAttribute("name");
9973 if (s.size() > 0)
9974 projectName = s;
9975 s = project->getAttribute("default");
9976 if (s.size() > 0)
9977 defaultTarget = s;
9978 s = project->getAttribute("basedir");
9979 if (s.size() > 0)
9980 baseDir = s;
9982 //######### PARSE MEMBERS
9983 std::vector<Element *> children = project->getChildren();
9984 for (unsigned int i=0 ; i<children.size() ; i++)
9985 {
9986 Element *elem = children[i];
9987 setLine(elem->getLine());
9988 String tagName = elem->getName();
9990 //########## DESCRIPTION
9991 if (tagName == "description")
9992 {
9993 description = parser.trim(elem->getValue());
9994 }
9996 //######### PROPERTY
9997 else if (tagName == "property")
9998 {
9999 if (!parseProperty(elem))
10000 return false;
10001 }
10003 //######### TARGET
10004 else if (tagName == "target")
10005 {
10006 String tname = elem->getAttribute("name");
10007 String tdesc = elem->getAttribute("description");
10008 String tdeps = elem->getAttribute("depends");
10009 String tif = elem->getAttribute("if");
10010 String tunless = elem->getAttribute("unless");
10011 Target target(*this);
10012 target.setName(tname);
10013 target.setDescription(tdesc);
10014 target.parseDependencies(tdeps);
10015 target.setIf(tif);
10016 target.setUnless(tunless);
10017 std::vector<Element *> telems = elem->getChildren();
10018 for (unsigned int i=0 ; i<telems.size() ; i++)
10019 {
10020 Element *telem = telems[i];
10021 Task breeder(*this);
10022 Task *task = breeder.createTask(telem, telem->getLine());
10023 if (!task)
10024 return false;
10025 allTasks.push_back(task);
10026 target.addTask(task);
10027 }
10029 //Check name
10030 if (tname.size() == 0)
10031 {
10032 error("no name for target");
10033 return false;
10034 }
10035 //Check for duplicate name
10036 if (targets.find(tname) != targets.end())
10037 {
10038 error("target '%s' already defined", tname.c_str());
10039 return false;
10040 }
10041 //more work than targets[tname]=target, but avoids default allocator
10042 targets.insert(std::make_pair<String, Target>(tname, target));
10043 }
10044 //######### none of the above
10045 else
10046 {
10047 error("unknown toplevel tag: <%s>", tagName.c_str());
10048 return false;
10049 }
10051 }
10053 std::map<String, Target>::iterator iter;
10054 for (iter = targets.begin() ; iter!= targets.end() ; iter++)
10055 {
10056 Target tgt = iter->second;
10057 std::vector<String> depList;
10058 if (!checkTargetDependencies(tgt, depList))
10059 {
10060 return false;
10061 }
10062 }
10065 delete root;
10066 status("######## PARSE COMPLETE");
10067 return true;
10068 }
10071 /**
10072 * Overload a <property>
10073 */
10074 bool Make::specifyProperty(const String &name, const String &value)
10075 {
10076 if (specifiedProperties.find(name) != specifiedProperties.end())
10077 {
10078 error("Property %s already specified", name.c_str());
10079 return false;
10080 }
10081 specifiedProperties[name] = value;
10082 return true;
10083 }
10087 /**
10088 *
10089 */
10090 bool Make::run()
10091 {
10092 if (!parseFile())
10093 return false;
10095 if (!execute())
10096 return false;
10098 return true;
10099 }
10104 /**
10105 * Get a formatted MM:SS.sss time elapsed string
10106 */
10107 static String
10108 timeDiffString(struct timeval &x, struct timeval &y)
10109 {
10110 long microsX = x.tv_usec;
10111 long secondsX = x.tv_sec;
10112 long microsY = y.tv_usec;
10113 long secondsY = y.tv_sec;
10114 if (microsX < microsY)
10115 {
10116 microsX += 1000000;
10117 secondsX -= 1;
10118 }
10120 int seconds = (int)(secondsX - secondsY);
10121 int millis = (int)((microsX - microsY)/1000);
10123 int minutes = seconds/60;
10124 seconds -= minutes*60;
10125 char buf[80];
10126 snprintf(buf, 79, "%dm %d.%03ds", minutes, seconds, millis);
10127 String ret = buf;
10128 return ret;
10130 }
10132 /**
10133 *
10134 */
10135 bool Make::run(const String &target)
10136 {
10137 status("####################################################");
10138 status("# %s", version().c_str());
10139 status("####################################################");
10140 struct timeval timeStart, timeEnd;
10141 ::gettimeofday(&timeStart, NULL);
10142 specifiedTarget = target;
10143 if (!run())
10144 return false;
10145 ::gettimeofday(&timeEnd, NULL);
10146 String timeStr = timeDiffString(timeEnd, timeStart);
10147 status("####################################################");
10148 status("# BuildTool Completed : %s", timeStr.c_str());
10149 status("####################################################");
10150 return true;
10151 }
10159 }// namespace buildtool
10160 //########################################################################
10161 //# M A I N
10162 //########################################################################
10164 typedef buildtool::String String;
10166 /**
10167 * Format an error message in printf() style
10168 */
10169 static void error(const char *fmt, ...)
10170 {
10171 va_list ap;
10172 va_start(ap, fmt);
10173 fprintf(stderr, "BuildTool error: ");
10174 vfprintf(stderr, fmt, ap);
10175 fprintf(stderr, "\n");
10176 va_end(ap);
10177 }
10180 static bool parseProperty(const String &s, String &name, String &val)
10181 {
10182 int len = s.size();
10183 int i;
10184 for (i=0 ; i<len ; i++)
10185 {
10186 char ch = s[i];
10187 if (ch == '=')
10188 break;
10189 name.push_back(ch);
10190 }
10191 if (i>=len || s[i]!='=')
10192 {
10193 error("property requires -Dname=value");
10194 return false;
10195 }
10196 i++;
10197 for ( ; i<len ; i++)
10198 {
10199 char ch = s[i];
10200 val.push_back(ch);
10201 }
10202 return true;
10203 }
10206 /**
10207 * Compare a buffer with a key, for the length of the key
10208 */
10209 static bool sequ(const String &buf, const char *key)
10210 {
10211 int len = buf.size();
10212 for (int i=0 ; key[i] && i<len ; i++)
10213 {
10214 if (key[i] != buf[i])
10215 return false;
10216 }
10217 return true;
10218 }
10220 static void usage(int argc, char **argv)
10221 {
10222 printf("usage:\n");
10223 printf(" %s [options] [target]\n", argv[0]);
10224 printf("Options:\n");
10225 printf(" -help, -h print this message\n");
10226 printf(" -version print the version information and exit\n");
10227 printf(" -file <file> use given buildfile\n");
10228 printf(" -f <file> ''\n");
10229 printf(" -D<property>=<value> use value for given property\n");
10230 }
10235 /**
10236 * Parse the command-line args, get our options,
10237 * and run this thing
10238 */
10239 static bool parseOptions(int argc, char **argv)
10240 {
10241 if (argc < 1)
10242 {
10243 error("Cannot parse arguments");
10244 return false;
10245 }
10247 buildtool::Make make;
10249 String target;
10251 //char *progName = argv[0];
10252 for (int i=1 ; i<argc ; i++)
10253 {
10254 String arg = argv[i];
10255 if (arg.size()>1 && arg[0]=='-')
10256 {
10257 if (arg == "-h" || arg == "-help")
10258 {
10259 usage(argc,argv);
10260 return true;
10261 }
10262 else if (arg == "-version")
10263 {
10264 printf("%s", make.version().c_str());
10265 return true;
10266 }
10267 else if (arg == "-f" || arg == "-file")
10268 {
10269 if (i>=argc)
10270 {
10271 usage(argc, argv);
10272 return false;
10273 }
10274 i++; //eat option
10275 make.setURI(argv[i]);
10276 }
10277 else if (arg.size()>2 && sequ(arg, "-D"))
10278 {
10279 String s = arg.substr(2, arg.size());
10280 String name, value;
10281 if (!parseProperty(s, name, value))
10282 {
10283 usage(argc, argv);
10284 return false;
10285 }
10286 if (!make.specifyProperty(name, value))
10287 return false;
10288 }
10289 else
10290 {
10291 error("Unknown option:%s", arg.c_str());
10292 return false;
10293 }
10294 }
10295 else
10296 {
10297 if (target.size()>0)
10298 {
10299 error("only one initial target");
10300 usage(argc, argv);
10301 return false;
10302 }
10303 target = arg;
10304 }
10305 }
10307 //We have the options. Now execute them
10308 if (!make.run(target))
10309 return false;
10311 return true;
10312 }
10317 /*
10318 static bool runMake()
10319 {
10320 buildtool::Make make;
10321 if (!make.run())
10322 return false;
10323 return true;
10324 }
10327 static bool pkgConfigTest()
10328 {
10329 buildtool::PkgConfig pkgConfig;
10330 if (!pkgConfig.readFile("gtk+-2.0.pc"))
10331 return false;
10332 return true;
10333 }
10337 static bool depTest()
10338 {
10339 buildtool::DepTool deptool;
10340 deptool.setSourceDirectory("/dev/ink/inkscape/src");
10341 if (!deptool.generateDependencies("build.dep"))
10342 return false;
10343 std::vector<buildtool::FileRec> res =
10344 deptool.loadDepFile("build.dep");
10345 if (res.size() == 0)
10346 return false;
10347 return true;
10348 }
10350 static bool popenTest()
10351 {
10352 buildtool::Make make;
10353 buildtool::String out, err;
10354 bool ret = make.executeCommand("gcc xx.cpp", "", out, err);
10355 printf("Popen test:%d '%s' '%s'\n", ret, out.c_str(), err.c_str());
10356 return true;
10357 }
10360 static bool propFileTest()
10361 {
10362 buildtool::Make make;
10363 make.parsePropertyFile("test.prop", "test.");
10364 return true;
10365 }
10366 */
10368 int main(int argc, char **argv)
10369 {
10371 if (!parseOptions(argc, argv))
10372 return 1;
10373 /*
10374 if (!popenTest())
10375 return 1;
10377 if (!depTest())
10378 return 1;
10379 if (!propFileTest())
10380 return 1;
10381 if (runMake())
10382 return 1;
10383 */
10384 return 0;
10385 }
10388 //########################################################################
10389 //# E N D
10390 //########################################################################