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 )
27 # include <sys/stat.h>
28 # define MAX_PATH PATH_MAX
36 #define MAX_PATH _MAX_PATH
43 #define getcwd _getcwd
46 static const char* WS
= " \t\r\n";
47 static const char* WSEQ
= " =\t\r\n";
49 string working_directory
;
51 XMLException::XMLException (
52 const std::string
& location
,
53 const char* format
, ... )
56 va_start ( args
, format
);
57 SetExceptionV ( location
, format
, args
);
61 void XMLException::SetExceptionV ( const std::string
& location
, const char* format
, va_list args
)
63 _e
= location
+ ": " + ssvprintf(format
,args
);
66 void XMLException::SetException ( const std::string
& location
, const char* format
, ... )
69 va_start ( args
, format
);
70 SetExceptionV ( location
, format
, args
);
74 XMLIncludes::~XMLIncludes()
76 for ( size_t i
= 0; i
< this->size(); i
++ )
81 InitWorkingDirectory()
83 // store the current directory for path calculations
84 working_directory
.resize ( MAX_PATH
);
85 working_directory
[0] = 0;
86 getcwd ( &working_directory
[0], working_directory
.size() );
87 working_directory
.resize ( strlen ( working_directory
.c_str() ) );
98 return _filelengthi64 ( _fileno(f
) );
101 struct stat file_stat
;
102 if ( fstat(fileno(f
), &file_stat
) != 0 )
104 struct stat64 file_stat
;
105 if ( fstat64(fileno(f
), &file_stat
) != 0 )
106 # endif // __FreeBSD__
108 return file_stat
.st_size
;
114 if ( !working_directory
.size() )
115 InitWorkingDirectory();
116 string
s ( working_directory
);
117 const char* p
= strtok ( &s
[0], "/\\" );
121 path
.push_back ( p
);
122 p
= strtok ( NULL
, "/\\" );
126 Path::Path ( const Path
& cwd
, const string
& file
)
128 string
s ( cwd
.Fixup ( file
, false ) );
129 const char* p
= strtok ( &s
[0], "/\\" );
133 path
.push_back ( p
);
134 p
= strtok ( NULL
, "/\\" );
139 Path::Fixup ( const string
& file
, bool include_filename
) const
141 if ( strchr ( "/\\", file
[0] )
143 // this squirreliness is b/c win32 has drive letters and *nix doesn't...
150 vector
<string
> pathtmp ( path
);
152 const char* prev
= strtok ( &tmp
[0], "/\\" );
153 const char* p
= strtok ( NULL
, "/\\" );
156 if ( !strcmp ( prev
, "." ) )
158 else if ( !strcmp ( prev
, ".." ) )
160 // this squirreliness is b/c win32 has drive letters and *nix doesn't...
162 if ( pathtmp
.size() > 1 )
164 if ( pathtmp
.size() )
166 pathtmp
.resize ( pathtmp
.size() - 1 );
169 pathtmp
.push_back ( prev
);
171 p
= strtok ( NULL
, "/\\" );
173 if ( include_filename
)
174 pathtmp
.push_back ( prev
);
176 // reuse tmp variable to return recombined path
178 for ( size_t i
= 0; i
< pathtmp
.size(); i
++ )
180 // this squirreliness is b/c win32 has drive letters and *nix doesn't...
192 Path::RelativeFromWorkingDirectory ()
195 for ( size_t i
= 0; i
< path
.size(); i
++ )
197 out
+= "/" + path
[i
];
199 return RelativeFromWorkingDirectory ( out
);
203 Path::RelativeFromWorkingDirectory ( const string
& path
)
205 return Path::RelativeFromDirectory ( path
, working_directory
);
209 Path::RelativeFromDirectory (
211 const string
& base_directory
)
213 vector
<string
> vbase
, vpath
, vout
;
214 Path::Split ( vbase
, base_directory
, true );
215 Path::Split ( vpath
, path
, true );
217 // this squirreliness is b/c win32 has drive letters and *nix doesn't...
218 // not possible to do relative across different drive letters
220 char path_driveletter
= (path
[1] == ':') ? toupper(path
[0]) : 0;
221 char base_driveletter
= (base_directory
[1] == ':') ? toupper(base_directory
[0]) : 0;
222 if ( path_driveletter
!= base_driveletter
)
227 while ( i
< vbase
.size() && i
< vpath
.size() && vbase
[i
] == vpath
[i
] )
230 // did we go through all of the path?
231 if ( vbase
.size() == vpath
.size() && i
== vpath
.size() )
234 if ( i
< vbase
.size() )
236 // path goes above our base directory, we will need some ..'s
237 for ( size_t j
= i
; j
< vbase
.size(); j
++ )
238 vout
.push_back ( ".." );
241 while ( i
< vpath
.size() )
242 vout
.push_back ( vpath
[i
++] );
244 // now merge vout into a string again
245 string out
= vout
[0];
246 for ( i
= 1; i
< vout
.size(); i
++ )
248 out
+= "/" + vout
[i
];
260 const char* prev
= strtok ( &s
[0], "/\\" );
261 const char* p
= strtok ( NULL
, "/\\" );
265 if ( strcmp ( prev
, "." ) )
266 out
.push_back ( prev
);
268 p
= strtok ( NULL
, "/\\" );
270 if ( include_last
&& strcmp ( prev
, "." ) )
271 out
.push_back ( prev
);
272 // special-case where path only has "."
273 // don't move this check up higher as it might miss
274 // some funny paths...
275 if ( !out
.size() && !strcmp ( prev
, "." ) )
276 out
.push_back ( "." );
291 XMLFile::open ( const string
& filename_
)
294 FILE* f
= fopen ( filename_
.c_str(), "rb" );
297 unsigned long len
= (unsigned long)filelen(f
);
299 fread ( &_buf
[0], 1, len
, f
);
303 _filename
= filename_
;
308 // next_token() moves the pointer to next token, which may be
309 // an xml element or a text element, basically it's a glorified
310 // skipspace, normally the user of this class won't need to call
313 XMLFile::next_token()
315 _p
+= strspn ( _p
, WS
);
319 XMLFile::next_is_text()
325 XMLFile::more_tokens ()
330 // get_token() is used to return a token, and move the pointer
333 XMLFile::get_token ( string
& token
)
336 if ( !strncmp ( _p
, "<!--", 4 ) )
338 tokend
= strstr ( _p
, "-->" );
344 else if ( !strncmp ( _p
, "<?", 2 ) )
346 tokend
= strstr ( _p
, "?>" );
352 else if ( *_p
== '<' )
354 tokend
= strchr ( _p
, '>' );
362 tokend
= strchr ( _p
, '<' );
365 while ( tokend
> _p
&& isspace(tokend
[-1]) )
370 token
= string ( _p
, tokend
-_p
);
377 XMLFile::get_token ( string
& token
, string
& location
)
379 location
= Location();
380 return get_token ( token
);
384 XMLFile::Location() const
387 const char* p
= strchr ( _buf
.c_str(), '\n' );
388 while ( p
&& p
< _p
)
391 p
= strchr ( p
+1, '\n' );
393 return ssprintf ( "%s(%i)",_filename
.c_str(), line
);
396 XMLAttribute::XMLAttribute()
400 XMLAttribute::XMLAttribute(
402 const string
& value_
)
403 : name(name_
), value(value_
)
407 XMLAttribute::XMLAttribute ( const XMLAttribute
& src
)
408 : name(src
.name
), value(src
.value
)
413 XMLAttribute
& XMLAttribute::operator = ( const XMLAttribute
& src
)
420 XMLElement::XMLElement (
422 const string
& location
)
423 : xmlFile ( xmlFile
),
424 location ( location
),
425 parentElement ( NULL
)
429 XMLElement::~XMLElement()
432 for ( i
= 0; i
< attributes
.size(); i
++ )
433 delete attributes
[i
];
434 for ( i
= 0; i
< subElements
.size(); i
++ )
435 delete subElements
[i
];
439 XMLElement::AddSubElement ( XMLElement
* e
)
441 subElements
.push_back ( e
);
442 e
->parentElement
= this;
446 // This function takes a single xml tag ( i.e. beginning with '<' and
447 // ending with '>', and parses out it's tag name and constituent
449 // Return Value: returns true if you need to look for a </tag> for
450 // the one it just parsed...
456 const char* p
= token
.c_str();
457 assert ( *p
== '<' );
459 p
+= strspn ( p
, WS
);
461 // check if this is a comment
462 if ( !strncmp ( p
, "!--", 3 ) )
466 return false; // never look for end tag to a comment
469 end_tag
= ( *p
== '/' );
473 p
+= strspn ( p
, WS
);
475 const char* end
= strpbrk ( p
, WS
);
478 end
= strpbrk ( p
, "/>" );
481 name
= string ( p
, end
-p
);
483 p
+= strspn ( p
, WS
);
484 while ( *p
!= '>' && *p
!= '/' )
486 end
= strpbrk ( p
, WSEQ
);
489 end
= strpbrk ( p
, "/>" );
492 string
attribute ( p
, end
-p
), value
;
494 p
+= strspn ( p
, WS
);
498 p
+= strspn ( p
, WS
);
500 if ( strchr ( "\"'", *p
) )
503 end
= strchr ( p
, quote
);
507 end
= strpbrk ( p
, WS
);
511 end
= strchr ( p
, '>' );
513 if ( end
[-1] == '/' )
516 value
= string ( p
, end
-p
);
518 if ( quote
&& *p
== quote
)
520 p
+= strspn ( p
, WS
);
522 else if ( name
[0] != '!' )
524 throw XMLSyntaxErrorException (
526 "attributes must have values" );
528 attributes
.push_back ( new XMLAttribute ( attribute
, value
) );
530 return !( *p
== '/' ) && !end_tag
;
534 XMLElement::GetAttribute (
535 const string
& attribute
,
538 // this would be faster with a tree-based container, but our attribute
539 // lists are likely to stay so short as to not be an issue.
540 for ( size_t i
= 0; i
< attributes
.size(); i
++ )
542 if ( attribute
== attributes
[i
]->name
)
543 return attributes
[i
];
547 throw XMLRequiredAttributeNotFoundException (
556 XMLElement::GetAttribute (
557 const string
& attribute
,
558 bool required
) const
560 // this would be faster with a tree-based container, but our attribute
561 // lists are likely to stay so short as to not be an issue.
562 for ( size_t i
= 0; i
< attributes
.size(); i
++ )
564 if ( attribute
== attributes
[i
]->name
)
565 return attributes
[i
];
569 throw XMLRequiredAttributeNotFoundException (
578 XMLElement::FindElement ( const std::string
& type
, int prev
) const
580 int done
= subElements
.size();
581 while ( ++prev
< done
)
583 XMLElement
* e
= subElements
[prev
];
584 if ( e
->name
== type
)
591 XMLElement::GetElements (
592 const std::string
& type
,
593 std::vector
<XMLElement
*>& v
)
595 int find
= FindElement ( type
);
599 v
.push_back ( subElements
[find
] );
600 find
= FindElement ( type
, find
);
606 XMLElement::GetElements (
607 const std::string
& type
,
608 std::vector
<const XMLElement
*>& v
) const
610 int find
= FindElement ( type
);
614 v
.push_back ( subElements
[find
] );
615 find
= FindElement ( type
, find
);
621 // This function reads a "token" from the file loaded in XMLFile
622 // if it finds a tag that is non-singular, it parses sub-elements and/or
623 // inner text into the XMLElement that it is building to return.
624 // Return Value: an XMLElement allocated via the new operator that contains
625 // it's parsed data. Keep calling this function until it returns NULL
630 XMLIncludes
* includes
,
632 bool* pend_tag
= NULL
)
634 string token
, location
;
635 if ( !f
.get_token(token
,location
) )
637 bool end_tag
, is_include
= false;
642 || !strncmp ( token
.c_str (), "<!--", 4 )
643 || !strncmp ( token
.c_str (), "<?", 2 )
646 if ( token
[0] != '<' )
648 throw XMLSyntaxErrorException (
650 "expecting xml tag, not '%s'",
653 if ( !f
.get_token ( token
, location
) )
657 XMLElement
* e
= new XMLElement (
660 bool bNeedEnd
= e
->Parse ( token
, end_tag
);
662 if ( e
->name
== "xi:include" && includes
)
665 att
= e
->GetAttribute ( "href", true );
667 string
includeFile ( path
.Fixup ( att
->value
, true ) );
668 string
topIncludeFile (
669 Path::RelativeFromWorkingDirectory ( includeFile
) );
670 includes
->push_back (
671 new XMLInclude ( e
, path
, topIncludeFile
) );
682 throw XMLSyntaxErrorException (
684 "end tag '%s' not expected",
690 bool bThisMixingErrorReported
= false;
691 while ( f
.more_tokens () )
693 if ( f
.next_is_text () )
695 if ( !f
.get_token ( token
, location
) || token
.size () == 0 )
697 throw XMLInvalidBuildFileException (
699 "internal tool error - get_token() failed when more_tokens() returned true" );
702 if ( e
->subElements
.size() && !bThisMixingErrorReported
)
704 throw XMLSyntaxErrorException (
706 "mixing of inner text with sub elements" );
707 bThisMixingErrorReported
= true;
709 if ( strchr ( token
.c_str (), '>' ) )
711 throw XMLSyntaxErrorException (
713 "invalid symbol '>'" );
715 if ( e
->value
.size() > 0 )
717 throw XMLSyntaxErrorException (
719 "multiple instances of inner text" );
720 e
->value
+= " " + token
;
727 XMLElement
* e2
= XMLParse (
728 f
, is_include
? NULL
: includes
, path
, &end_tag
);
731 string e_location
= e
->location
;
732 string e_name
= e
->name
;
734 throw XMLInvalidBuildFileException (
736 "end of file found looking for end tag: </%s>",
742 if ( e
->name
!= e2
->name
)
744 string e2_location
= e2
->location
;
745 string e_name
= e
->name
;
746 string e2_name
= e2
->name
;
749 throw XMLSyntaxErrorException (
751 "end tag name mismatch - found </%s> but was expecting </%s>",
759 if ( e
->value
.size () > 0 && !bThisMixingErrorReported
)
761 string e_location
= e
->location
;
763 throw XMLSyntaxErrorException (
765 "mixing of inner text with sub elements" );
766 bThisMixingErrorReported
= true;
768 e
->AddSubElement ( e2
);
778 XMLIncludes
& includes
,
783 XMLElement
* e
= XMLParse ( f
, &includes
, path
);
786 head
.AddSubElement ( e
);
793 XMLIncludes
& includes
)
796 att
= include
.e
->GetAttribute("href", true);
799 string
file ( include
.path
.Fixup(att
->value
, true) );
800 string
top_file ( Path::RelativeFromWorkingDirectory ( file
) );
801 include
.e
->attributes
.push_back ( new XMLAttribute ( "top_href", top_file
) );
802 XMLFile
* fInc
= new XMLFile();
803 if ( !fInc
->open ( file
) )
805 include
.fileExists
= false;
806 // look for xi:fallback element
807 for ( size_t i
= 0; i
< include
.e
->subElements
.size (); i
++ )
809 XMLElement
* e2
= include
.e
->subElements
[i
];
810 if ( e2
->name
== "xi:fallback" )
812 // now look for xi:include below...
813 for ( i
= 0; i
< e2
->subElements
.size (); i
++ )
815 XMLElement
* e3
= e2
->subElements
[i
];
816 if ( e3
->name
== "xi:include" )
818 att
= e3
->GetAttribute ( "href", true );
821 include
.path
.Fixup ( att
->value
, true ) );
822 string
topIncludeFile (
823 Path::RelativeFromWorkingDirectory ( includeFile
) );
824 XMLInclude
* fallbackInclude
=
825 new XMLInclude ( e3
, include
.path
, topIncludeFile
);
826 return XMLLoadInclude (
827 *fallbackInclude
, includes
);
830 throw XMLInvalidBuildFileException (
832 "<xi:fallback> must have a <xi:include> sub-element" );
840 include
.fileExists
= true;
841 XMLElement
* new_e
= new XMLElement (
843 include
.e
->location
);
844 new_e
->name
= "xi:included";
845 Path
path2 ( include
.path
, att
->value
);
846 XMLReadFile ( *fInc
, *new_e
, includes
, path2
);
853 const string
& filename
,
855 XMLIncludes
& includes
)
857 XMLFile
* f
= new XMLFile();
859 if ( !f
->open ( filename
) )
861 throw XMLFileNotFoundException ( "(virtual)", filename
);
865 XMLElement
* head
= new XMLElement ( f
, "(virtual)" );
867 XMLReadFile ( *f
, *head
, includes
, path
);
869 for ( size_t i
= 0; i
< includes
.size (); i
++ )
871 XMLElement
* e
= includes
[i
]->e
;
872 XMLElement
* e2
= XMLLoadInclude ( *includes
[i
], includes
);
875 throw XMLFileNotFoundException (
877 e
->GetAttribute ( "top_href", true )->value
);
879 XMLElement
* parent
= e
->parentElement
;
880 XMLElement
** parent_container
= NULL
;
883 string location
= e
->location
;
885 throw XMLException ( location
, "internal tool error: xi:include doesn't have a parent" );
888 for ( size_t j
= 0; j
< parent
->subElements
.size (); j
++ )
890 if ( parent
->subElements
[j
] == e
)
892 parent_container
= &parent
->subElements
[j
];
896 if ( !parent_container
)
898 string location
= e
->location
;
900 throw XMLException ( location
, "internal tool error: couldn't find xi:include in parent's sub-elements" );
903 // replace inclusion tree with the imported tree
904 e2
->parentElement
= e
->parentElement
;
906 e2
->attributes
= e
->attributes
;
907 *parent_container
= e2
;
908 e
->attributes
.resize ( 0 );
915 XMLLoadFile ( const string
& filename
)
918 XMLIncludes includes
;
919 return XMLLoadFile ( filename
, path
, includes
);