2 * Copyright (C) 2005 Casper S. Hornstrup
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #pragma warning ( disable : 4786 )
30 // Some hosts don't define PATH_MAX in unistd.h
31 #if !defined(PATH_MAX)
35 #define MAX_PATH PATH_MAX
46 #define MAX_PATH _MAX_PATH
53 #define getcwd _getcwd
56 static const char* WS
= " \t\r\n";
57 static const char* WSEQ
= " =\t\r\n";
59 string working_directory
;
61 XMLException::XMLException (
62 const std::string
& location
,
63 const char* format
, ... )
66 va_start ( args
, format
);
67 SetExceptionV ( location
, format
, args
);
71 void XMLException::SetExceptionV ( const std::string
& location
, const char* format
, va_list args
)
73 _e
= location
+ ": " + ssvprintf(format
,args
);
76 void XMLException::SetException ( const std::string
& location
, const char* format
, ... )
79 va_start ( args
, format
);
80 SetExceptionV ( location
, format
, args
);
84 XMLIncludes::~XMLIncludes()
86 for ( size_t i
= 0; i
< this->size(); i
++ )
91 InitWorkingDirectory()
93 // store the current directory for path calculations
94 working_directory
.resize ( MAX_PATH
);
95 working_directory
[0] = 0;
96 getcwd ( &working_directory
[0], working_directory
.size() );
97 working_directory
.resize ( strlen ( working_directory
.c_str() ) );
108 return _filelengthi64 ( _fileno(f
) );
110 # if defined(__FreeBSD__) || defined(__APPLE__) || defined(__CYGWIN__)
111 struct stat file_stat
;
112 if ( fstat(fileno(f
), &file_stat
) != 0 )
114 struct stat64 file_stat
;
115 if ( fstat64(fileno(f
), &file_stat
) != 0 )
116 # endif // __FreeBSD__
118 return file_stat
.st_size
;
124 if ( !working_directory
.size() )
125 InitWorkingDirectory();
126 string
s ( working_directory
);
127 const char* p
= strtok ( &s
[0], "/\\" );
131 path
.push_back ( p
);
132 p
= strtok ( NULL
, "/\\" );
136 Path::Path ( const Path
& cwd
, const string
& file
)
138 string
s ( cwd
.Fixup ( file
, false ) );
139 const char* p
= strtok ( &s
[0], "/\\" );
143 path
.push_back ( p
);
144 p
= strtok ( NULL
, "/\\" );
149 Path::Fixup ( const string
& file
, bool include_filename
) const
151 if ( strchr ( "/\\", file
[0] )
153 // this squirreliness is b/c win32 has drive letters and *nix doesn't...
160 vector
<string
> pathtmp ( path
);
162 const char* prev
= strtok ( &tmp
[0], "/\\" );
163 const char* p
= strtok ( NULL
, "/\\" );
166 if ( !strcmp ( prev
, "." ) )
168 else if ( !strcmp ( prev
, ".." ) )
170 // this squirreliness is b/c win32 has drive letters and *nix doesn't...
172 if ( pathtmp
.size() > 1 )
174 if ( pathtmp
.size() )
176 pathtmp
.resize ( pathtmp
.size() - 1 );
179 pathtmp
.push_back ( prev
);
181 p
= strtok ( NULL
, "/\\" );
183 if ( include_filename
)
184 pathtmp
.push_back ( prev
);
186 // reuse tmp variable to return recombined path
188 for ( size_t i
= 0; i
< pathtmp
.size(); i
++ )
190 // this squirreliness is b/c win32 has drive letters and *nix doesn't...
202 Path::RelativeFromWorkingDirectory ()
205 for ( size_t i
= 0; i
< path
.size(); i
++ )
207 out
+= "/" + path
[i
];
209 return RelativeFromWorkingDirectory ( out
);
213 Path::RelativeFromWorkingDirectory ( const string
& path
)
215 return Path::RelativeFromDirectory ( path
, working_directory
);
219 Path::RelativeFromDirectory (
221 const string
& base_directory
)
223 vector
<string
> vbase
, vpath
, vout
;
224 Path::Split ( vbase
, base_directory
, true );
225 Path::Split ( vpath
, path
, true );
227 // this squirreliness is b/c win32 has drive letters and *nix doesn't...
228 // not possible to do relative across different drive letters
230 char path_driveletter
= (path
[1] == ':') ? toupper(path
[0]) : 0;
231 char base_driveletter
= (base_directory
[1] == ':') ? toupper(base_directory
[0]) : 0;
232 if ( path_driveletter
!= base_driveletter
)
237 while ( i
< vbase
.size() && i
< vpath
.size() && vbase
[i
] == vpath
[i
] )
240 // did we go through all of the path?
241 if ( vbase
.size() == vpath
.size() && i
== vpath
.size() )
244 if ( i
< vbase
.size() )
246 // path goes above our base directory, we will need some ..'s
247 for ( size_t j
= i
; j
< vbase
.size(); j
++ )
248 vout
.push_back ( ".." );
251 while ( i
< vpath
.size() )
252 vout
.push_back ( vpath
[i
++] );
254 // now merge vout into a string again
255 string out
= vout
[0];
256 for ( i
= 1; i
< vout
.size(); i
++ )
258 out
+= "/" + vout
[i
];
270 const char* prev
= strtok ( &s
[0], "/\\" );
271 const char* p
= strtok ( NULL
, "/\\" );
275 if ( strcmp ( prev
, "." ) )
276 out
.push_back ( prev
);
278 p
= strtok ( NULL
, "/\\" );
280 if ( include_last
&& strcmp ( prev
, "." ) )
281 out
.push_back ( prev
);
282 // special-case where path only has "."
283 // don't move this check up higher as it might miss
284 // some funny paths...
285 if ( !out
.size() && !strcmp ( prev
, "." ) )
286 out
.push_back ( "." );
301 XMLFile::open ( const string
& filename_
)
304 FILE* f
= fopen ( filename_
.c_str(), "rb" );
307 unsigned long len
= (unsigned long)filelen(f
);
309 fread ( &_buf
[0], 1, len
, f
);
313 _filename
= filename_
;
318 // next_token() moves the pointer to next token, which may be
319 // an xml element or a text element, basically it's a glorified
320 // skipspace, normally the user of this class won't need to call
323 XMLFile::next_token()
325 _p
+= strspn ( _p
, WS
);
329 XMLFile::next_is_text()
335 XMLFile::more_tokens ()
340 // get_token() is used to return a token, and move the pointer
343 XMLFile::get_token ( string
& token
)
346 if ( !strncmp ( _p
, "<!--", 4 ) )
348 tokend
= strstr ( _p
, "-->" );
354 else if ( !strncmp ( _p
, "<?", 2 ) )
356 tokend
= strstr ( _p
, "?>" );
362 else if ( *_p
== '<' )
364 tokend
= strchr ( _p
, '>' );
372 tokend
= strchr ( _p
, '<' );
375 while ( tokend
> _p
&& isspace(tokend
[-1]) )
380 token
= string ( _p
, tokend
-_p
);
387 XMLFile::get_token ( string
& token
, string
& location
)
389 location
= Location();
390 return get_token ( token
);
394 XMLFile::Location() const
397 const char* p
= strchr ( _buf
.c_str(), '\n' );
398 while ( p
&& p
< _p
)
401 p
= strchr ( p
+1, '\n' );
403 return ssprintf ( "%s(%i)",_filename
.c_str(), line
);
406 XMLAttribute::XMLAttribute()
410 XMLAttribute::XMLAttribute(
412 const string
& value_
)
413 : name(name_
), value(value_
)
417 XMLAttribute::XMLAttribute ( const XMLAttribute
& src
)
418 : name(src
.name
), value(src
.value
)
423 XMLAttribute
& XMLAttribute::operator = ( const XMLAttribute
& src
)
430 XMLElement::XMLElement (
432 const string
& location
)
433 : xmlFile ( xmlFile
),
434 location ( location
),
435 parentElement ( NULL
)
439 XMLElement::~XMLElement()
442 for ( i
= 0; i
< attributes
.size(); i
++ )
443 delete attributes
[i
];
444 for ( i
= 0; i
< subElements
.size(); i
++ )
445 delete subElements
[i
];
449 XMLElement::AddSubElement ( XMLElement
* e
)
451 subElements
.push_back ( e
);
452 e
->parentElement
= this;
456 // This function takes a single xml tag ( i.e. beginning with '<' and
457 // ending with '>', and parses out it's tag name and constituent
459 // Return Value: returns true if you need to look for a </tag> for
460 // the one it just parsed...
466 const char* p
= token
.c_str();
467 assert ( *p
== '<' );
469 p
+= strspn ( p
, WS
);
471 // check if this is a comment
472 if ( !strncmp ( p
, "!--", 3 ) )
476 return false; // never look for end tag to a comment
479 end_tag
= ( *p
== '/' );
483 p
+= strspn ( p
, WS
);
485 const char* end
= strpbrk ( p
, WS
);
488 end
= strpbrk ( p
, "/>" );
491 name
= string ( p
, end
-p
);
493 p
+= strspn ( p
, WS
);
494 while ( *p
!= '>' && *p
!= '/' )
496 end
= strpbrk ( p
, WSEQ
);
499 end
= strpbrk ( p
, "/>" );
502 string
attribute ( p
, end
-p
), value
;
504 p
+= strspn ( p
, WS
);
508 p
+= strspn ( p
, WS
);
510 if ( strchr ( "\"'", *p
) )
513 end
= strchr ( p
, quote
);
517 end
= strpbrk ( p
, WS
);
521 end
= strchr ( p
, '>' );
523 if ( end
[-1] == '/' )
526 value
= string ( p
, end
-p
);
528 if ( quote
&& *p
== quote
)
530 p
+= strspn ( p
, WS
);
532 else if ( name
[0] != '!' )
534 throw XMLSyntaxErrorException (
536 "attributes must have values" );
538 attributes
.push_back ( new XMLAttribute ( attribute
, value
) );
540 return !( *p
== '/' ) && !end_tag
;
544 XMLElement::GetAttribute (
545 const string
& attribute
,
548 // this would be faster with a tree-based container, but our attribute
549 // lists are likely to stay so short as to not be an issue.
550 for ( size_t i
= 0; i
< attributes
.size(); i
++ )
552 if ( attribute
== attributes
[i
]->name
)
553 return attributes
[i
];
557 throw XMLRequiredAttributeNotFoundException (
566 XMLElement::GetAttribute (
567 const string
& attribute
,
568 bool required
) const
570 // this would be faster with a tree-based container, but our attribute
571 // lists are likely to stay so short as to not be an issue.
572 for ( size_t i
= 0; i
< attributes
.size(); i
++ )
574 if ( attribute
== attributes
[i
]->name
)
575 return attributes
[i
];
579 throw XMLRequiredAttributeNotFoundException (
588 XMLElement::FindElement ( const std::string
& type
, int prev
) const
590 int done
= subElements
.size();
591 while ( ++prev
< done
)
593 XMLElement
* e
= subElements
[prev
];
594 if ( e
->name
== type
)
601 XMLElement::GetElements (
602 const std::string
& type
,
603 std::vector
<XMLElement
*>& v
)
605 int find
= FindElement ( type
);
609 v
.push_back ( subElements
[find
] );
610 find
= FindElement ( type
, find
);
616 XMLElement::GetElements (
617 const std::string
& type
,
618 std::vector
<const XMLElement
*>& v
) const
620 int find
= FindElement ( type
);
624 v
.push_back ( subElements
[find
] );
625 find
= FindElement ( type
, find
);
631 // This function reads a "token" from the file loaded in XMLFile
632 // if it finds a tag that is non-singular, it parses sub-elements and/or
633 // inner text into the XMLElement that it is building to return.
634 // Return Value: an XMLElement allocated via the new operator that contains
635 // it's parsed data. Keep calling this function until it returns NULL
640 XMLIncludes
* includes
,
642 bool* pend_tag
= NULL
)
644 string token
, location
;
645 if ( !f
.get_token(token
,location
) )
647 bool end_tag
, is_include
= false;
652 || !strncmp ( token
.c_str (), "<!--", 4 )
653 || !strncmp ( token
.c_str (), "<?", 2 )
656 if ( token
[0] != '<' )
658 throw XMLSyntaxErrorException (
660 "expecting xml tag, not '%s'",
663 if ( !f
.get_token ( token
, location
) )
667 XMLElement
* e
= new XMLElement (
670 bool bNeedEnd
= e
->Parse ( token
, end_tag
);
672 if ( e
->name
== "xi:include" && includes
)
675 att
= e
->GetAttribute ( "href", true );
677 string
includeFile ( path
.Fixup ( att
->value
, true ) );
678 string
topIncludeFile (
679 Path::RelativeFromWorkingDirectory ( includeFile
) );
680 includes
->push_back (
681 new XMLInclude ( e
, path
, topIncludeFile
) );
692 throw XMLSyntaxErrorException (
694 "end tag '%s' not expected",
700 bool bThisMixingErrorReported
= false;
701 while ( f
.more_tokens () )
703 if ( f
.next_is_text () )
705 if ( !f
.get_token ( token
, location
) || token
.size () == 0 )
707 throw XMLInvalidBuildFileException (
709 "internal tool error - get_token() failed when more_tokens() returned true" );
712 if ( e
->subElements
.size() && !bThisMixingErrorReported
)
714 throw XMLSyntaxErrorException (
716 "mixing of inner text with sub elements" );
717 bThisMixingErrorReported
= true;
719 if ( strchr ( token
.c_str (), '>' ) )
721 throw XMLSyntaxErrorException (
723 "invalid symbol '>'" );
725 if ( e
->value
.size() > 0 )
727 throw XMLSyntaxErrorException (
729 "multiple instances of inner text" );
730 e
->value
+= " " + token
;
737 XMLElement
* e2
= XMLParse (
738 f
, is_include
? NULL
: includes
, path
, &end_tag
);
741 string e_location
= e
->location
;
742 string e_name
= e
->name
;
744 throw XMLInvalidBuildFileException (
746 "end of file found looking for end tag: </%s>",
752 if ( e
->name
!= e2
->name
)
754 string e2_location
= e2
->location
;
755 string e_name
= e
->name
;
756 string e2_name
= e2
->name
;
759 throw XMLSyntaxErrorException (
761 "end tag name mismatch - found </%s> but was expecting </%s>",
769 if ( e
->value
.size () > 0 && !bThisMixingErrorReported
)
771 string e_location
= e
->location
;
773 throw XMLSyntaxErrorException (
775 "mixing of inner text with sub elements" );
776 bThisMixingErrorReported
= true;
778 e
->AddSubElement ( e2
);
788 XMLIncludes
& includes
,
793 XMLElement
* e
= XMLParse ( f
, &includes
, path
);
796 head
.AddSubElement ( e
);
803 XMLIncludes
& includes
)
806 att
= include
.e
->GetAttribute("href", true);
809 string
file ( include
.path
.Fixup(att
->value
, true) );
810 string
top_file ( Path::RelativeFromWorkingDirectory ( file
) );
811 include
.e
->attributes
.push_back ( new XMLAttribute ( "top_href", top_file
) );
812 XMLFile
* fInc
= new XMLFile();
813 if ( !fInc
->open ( file
) )
815 include
.fileExists
= false;
816 // look for xi:fallback element
817 for ( size_t i
= 0; i
< include
.e
->subElements
.size (); i
++ )
819 XMLElement
* e2
= include
.e
->subElements
[i
];
820 if ( e2
->name
== "xi:fallback" )
822 // now look for xi:include below...
823 for ( i
= 0; i
< e2
->subElements
.size (); i
++ )
825 XMLElement
* e3
= e2
->subElements
[i
];
826 if ( e3
->name
== "xi:include" )
828 att
= e3
->GetAttribute ( "href", true );
831 include
.path
.Fixup ( att
->value
, true ) );
832 string
topIncludeFile (
833 Path::RelativeFromWorkingDirectory ( includeFile
) );
834 XMLInclude
* fallbackInclude
=
835 new XMLInclude ( e3
, include
.path
, topIncludeFile
);
837 XMLElement
* value
= XMLLoadInclude (*fallbackInclude
, includes
);
838 delete fallbackInclude
;
842 throw XMLInvalidBuildFileException (
844 "<xi:fallback> must have a <xi:include> sub-element" );
852 include
.fileExists
= true;
853 XMLElement
* new_e
= new XMLElement (
855 include
.e
->location
);
856 new_e
->name
= "xi:included";
857 Path
path2 ( include
.path
, att
->value
);
858 XMLReadFile ( *fInc
, *new_e
, includes
, path2
);
865 const string
& filename
,
867 XMLIncludes
& includes
)
869 XMLFile
* f
= new XMLFile();
871 if ( !f
->open ( filename
) )
874 throw XMLFileNotFoundException ( "(virtual)", filename
);
878 XMLElement
* head
= new XMLElement ( f
, "(virtual)" );
880 XMLReadFile ( *f
, *head
, includes
, path
);
882 for ( size_t i
= 0; i
< includes
.size (); i
++ )
884 XMLElement
* e
= includes
[i
]->e
;
885 XMLElement
* e2
= XMLLoadInclude ( *includes
[i
], includes
);
888 throw XMLFileNotFoundException (
890 e
->GetAttribute ( "top_href", true )->value
);
892 XMLElement
* parent
= e
->parentElement
;
893 XMLElement
** parent_container
= NULL
;
896 string location
= e
->location
;
899 throw XMLException ( location
, "internal tool error: xi:include doesn't have a parent" );
902 for ( size_t j
= 0; j
< parent
->subElements
.size (); j
++ )
904 if ( parent
->subElements
[j
] == e
)
906 parent_container
= &parent
->subElements
[j
];
910 if ( !parent_container
)
912 string location
= e
->location
;
915 throw XMLException ( location
, "internal tool error: couldn't find xi:include in parent's sub-elements" );
918 // replace inclusion tree with the imported tree
919 e2
->parentElement
= e
->parentElement
;
921 e2
->attributes
= e
->attributes
;
922 *parent_container
= e2
;
923 e
->attributes
.resize ( 0 );
931 XMLLoadFile ( const string
& filename
)
934 XMLIncludes includes
;
935 return XMLLoadFile ( filename
, path
, includes
);