- not needed anymore, seems like the bug was here, but switching to
[platform/upstream/libzypp.git] / zypp / PoolQuery.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/PoolQuery.cc
10  *
11 */
12 #include <iostream>
13 #include <sstream>
14 #include <boost/algorithm/string/replace.hpp>
15
16 #include "zypp/base/Gettext.h"
17 #include "zypp/base/Logger.h"
18 #include "zypp/base/Regex.h"
19 #include "zypp/base/Algorithm.h"
20 #include "zypp/base/String.h"
21 #include "zypp/repo/RepoException.h"
22
23 #include "zypp/sat/Pool.h"
24 #include "zypp/sat/Solvable.h"
25
26 #include "zypp/PoolQuery.h"
27
28 extern "C"
29 {
30 #include "satsolver/repo.h"
31 }
32
33 using namespace std;
34 using namespace zypp::sat;
35
36 ///////////////////////////////////////////////////////////////////
37 namespace zypp
38 { /////////////////////////////////////////////////////////////////
39
40   ///////////////////////////////////////////////////////////////////
41   //
42   //  CLASS NAME : PoolQuery::Impl
43   //
44   class PoolQuery::Impl
45   {
46   public:
47     Impl()
48       : _flags( SEARCH_ALL_REPOS | SEARCH_NOCASE | SEARCH_SUBSTRING )
49       , _status_flags(ALL)
50       , _match_word(false) 
51       , _require_all(false)
52       , _compiled(false)
53     {}
54     
55     ~Impl()
56     {}
57
58   public:
59     const_iterator begin() const;
60     const_iterator end() const;
61     
62     string asString() const;
63     
64     void compile() const;
65   private:
66     string createRegex(const StrContainer & container) const;
67
68   public:
69     /** Raw search strings. */
70     StrContainer _strings;
71     /** Regex-compiled search strings. */
72     mutable string _rcstrings;
73     mutable regex_t _regex;
74     /** Raw attributes */
75     AttrMap _attrs;
76     /** Regex-compiled attributes */
77     mutable CompiledAttrMap _rcattrs;
78     mutable map<sat::SolvAttr, regex_t> _rattrs;
79
80     /** Repos to search. */
81     StrContainer _repos;
82     /** Kinds to search */
83     Kinds _kinds;
84
85     /** Sat solver search flags */
86     int _flags;
87     /** Backup of search flags. compile() may change the flags if needed, so
88      * in order to reuse the query, the original flags need to be stored
89      * at the start of compile() */
90     mutable int _cflags;
91     /** Sat solver status flags */
92     PoolQuery::StatusFilter _status_flags;
93
94     bool _match_word;
95
96     bool _require_all;
97
98     mutable bool _compiled;
99
100   private:
101     friend Impl * rwcowClone<Impl>( const Impl * rhs );
102     /** clone for RWCOW_pointer */
103     Impl * clone() const
104     { return new Impl( *this ); }
105   };
106
107   
108   static void
109   compileRegex(regex_t * regex, const string & str, bool nocase)
110   {
111     /* We feed multiple lines eventually (e.g. authors or descriptions),
112        so set REG_NEWLINE. */
113     if (regcomp(regex, str.c_str(),
114         REG_EXTENDED | REG_NOSUB | REG_NEWLINE | (nocase ? REG_ICASE : 0)) != 0)
115       ZYPP_THROW(Exception(
116         str::form(_("Invalid regular expression '%s'"), str.c_str())));
117   }
118
119   struct MyInserter
120   {
121     MyInserter(PoolQuery::StrContainer & cont) : _cont(cont) {}
122     
123     bool operator()(const string & str)
124     {
125       _cont.insert(str);
126       return true;
127     }
128     
129     PoolQuery::StrContainer & _cont;
130   };
131
132   
133   struct EmptyFilter
134   {
135     bool operator()(const string & str)
136     {
137       return !str.empty();
138     }
139   };
140
141
142   void PoolQuery::Impl::compile() const
143   {
144     _cflags = _flags;
145
146     // 'different'         - will have to iterate through all and match by ourselves (slow)
147     // 'same'              - will pass the compiled string to dataiterator_init
148     // 'one-attr'          - will pass it to dataiterator_init
149     // 'one-non-regex-str' - will pass to dataiterator_init, set flag to SEARCH_STRING or SEARCH_SUBSTRING
150     
151     // // NO ATTRIBUTE
152     // else
153     //   for all _strings
154     //     create regex; store in _rcstrings; if more strings flag regex;
155     if (_attrs.empty())
156     {
157       _rcstrings = createRegex(_strings);
158       if (_strings.size() > 1)
159         _cflags = (_cflags & ~SEARCH_STRINGMASK) | SEARCH_REGEX;//setMatchRegex();
160     }
161
162     // // ONE ATTRIBUTE 
163     // else if _attrs is not empty but it contains just one attr
164     //   for all _strings and _attr[key] strings
165     //     create regex; store in _rcattrs; flag 'one-attr'; if more strings flag regex;
166     else if (_attrs.size() == 1)
167     {
168       StrContainer joined;
169       invokeOnEach(_strings.begin(), _strings.end(), EmptyFilter(), MyInserter(joined));
170       invokeOnEach(_attrs.begin()->second.begin(), _attrs.begin()->second.end(), EmptyFilter(), MyInserter(joined));
171       _rcstrings = createRegex(joined);
172       _rcattrs.insert(pair<sat::SolvAttr, string>(_attrs.begin()->first, string()));
173     }
174
175     // // MULTIPLE ATTRIBUTES
176     else
177     {
178       // check whether there are any per-attribute strings 
179       bool attrvals_empty = true;
180       for (AttrMap::const_iterator ai = _attrs.begin(); ai != _attrs.end(); ++ai)
181         if (!ai->second.empty())
182           for(StrContainer::const_iterator it = ai->second.begin();
183               it != ai->second.end(); it++)
184             if (!it->empty())
185             {
186               attrvals_empty = false;
187               goto attremptycheckend;
188             }
189 attremptycheckend:
190
191       // chceck whether the per-attribute strings are all the same
192       bool attrvals_thesame = true;
193       AttrMap::const_iterator ai = _attrs.begin();
194       const StrContainer & set1 = ai->second;
195       ++ai;
196       for (; ai != _attrs.end(); ++ai)
197       {
198         StrContainer result;
199         set_difference(
200           set1.begin(), set1.end(),
201           ai->second.begin(), ai->second.end(),
202           inserter(result, result.begin())/*, ltstr()*/);
203         if (!result.empty())
204         {
205           attrvals_thesame = false;
206           break;
207         }
208       }
209
210       // // THE SAME STRINGS FOR DIFFERENT ATTRS
211       // else if _attrs is not empty but it does not contain strings
212       //   for each key in _attrs take all _strings
213       //     create regex; store in _rcattrs and _rcstrings; flag 'same'; if more strings flag regex;
214       if (attrvals_empty || attrvals_thesame)
215       {
216         StrContainer joined;
217         if (attrvals_empty)
218         {
219           invokeOnEach(_strings.begin(), _strings.end(), EmptyFilter(), MyInserter(joined));
220           _rcstrings = createRegex(joined);
221         }
222         else
223         {
224           invokeOnEach(_strings.begin(), _strings.end(), EmptyFilter(), MyInserter(joined));
225           invokeOnEach(_attrs.begin()->second.begin(), _attrs.begin()->second.end(), EmptyFilter(), MyInserter(joined));
226           _rcstrings = createRegex(joined);
227         }
228         // copy the _attrs keys to _rcattrs
229         for_(ai, _attrs.begin(), _attrs.end())
230           _rcattrs.insert(pair<sat::SolvAttr, string>(ai->first, string()));
231
232         if ((_cflags & SEARCH_STRINGMASK) == SEARCH_REGEX)
233           compileRegex(&_regex, _rcstrings, _cflags & SEARCH_NOCASE);
234       }
235
236       // // DIFFERENT STRINGS FOR DIFFERENT ATTRS
237       // if _attrs is not empty and it contains non-empty vectors with non-empty strings
238       //   for each key in _attrs take all _strings + all _attrs[key] strings
239       //     create regex; store in _rcattrs; flag 'different'; if more strings flag regex;
240       else
241       {
242         for_(ai, _attrs.begin(), _attrs.end())
243         {
244           StrContainer joined;
245           invokeOnEach(_strings.begin(), _strings.end(), EmptyFilter(), MyInserter(joined));
246           invokeOnEach(ai->second.begin(), ai->second.end(), EmptyFilter(), MyInserter(joined));
247           string s = createRegex(joined);
248           _rcattrs.insert(pair<sat::SolvAttr, string>(ai->first, s));
249
250           if ((_cflags & SEARCH_STRINGMASK) == SEARCH_REGEX)
251           {
252             regex_t regex;
253             compileRegex(&regex, s, _cflags & SEARCH_NOCASE);
254             _rattrs.insert(pair<sat::SolvAttr, regex_t>(ai->first, regex));
255           }
256         }
257       }
258     }
259
260     // tell the Dataiterator to search only in one repo if only one specified
261     if (_repos.size() == 1)
262       _cflags &= ~SEARCH_ALL_REPOS;
263
264     _compiled = true;
265     
266     DBG << asString() << endl;
267   }
268
269   /**
270    * Converts '*' and '?' wildcards within str into their regex equivalents.
271    */
272   static string wildcards2regex(const string & str)
273   {
274     string regexed = str;
275
276     str::regex all("\\*"); // regex to search for '*'
277     str::regex one("\\?"); // regex to search for '?'
278     string r_all(".*"); // regex equivalent of '*'
279     string r_one(".");  // regex equivalent of '?'
280     string::size_type pos;
281
282     // replace all "*" in input with ".*"
283     for (pos = 0; (pos = regexed.find("*", pos)) != std::string::npos; pos+=2)
284       regexed = regexed.replace(pos, 1, r_all);
285
286     // replace all "?" in input with "."
287     for (pos = 0; (pos = regexed.find('?', pos)) != std::string::npos; ++pos)
288       regexed = regexed.replace(pos, 1, r_one);
289
290     DBG << " -> " << regexed << endl;
291
292     return regexed;
293   }
294
295 //! macro for word boundary tags for regexes
296 #define WB (_match_word ? string("\\b") : string())
297
298   string PoolQuery::Impl::createRegex(const StrContainer & container) const
299   {
300     string rstr;
301
302     if (container.empty())
303       return rstr;
304
305     if (container.size() == 1)
306     {
307       if (_match_word)
308         return ".*" + WB + *container.begin() + WB + ".*";
309
310       return *container.begin();
311     }
312
313     // multiple strings
314
315     bool use_wildcards = (_cflags & SEARCH_STRINGMASK) == SEARCH_GLOB;
316     StrContainer::const_iterator it = container.begin();
317     string tmp;
318
319     if (use_wildcards)
320       tmp = wildcards2regex(*it);
321
322     if (_require_all)
323     {
324       if (!(_cflags & SEARCH_STRING)) // not match exact
325         tmp += ".*" + WB + tmp;
326       rstr = "(?=" + tmp + ")";
327     }
328     else
329     {
330       if (_cflags & SEARCH_STRING) // match exact
331         rstr = "^";
332       else
333         rstr = ".*" + WB;
334
335       rstr += "(" + tmp;
336     }
337
338     ++it;
339
340     for (; it != container.end(); ++it)
341     {
342       if (use_wildcards)
343         tmp = wildcards2regex(*it);
344
345       if (_require_all)
346       {
347         if (!(_cflags & SEARCH_STRING)) // not match exact
348           tmp += ".*" + WB + tmp;
349         rstr += "(?=" + tmp + ")";
350       }
351       else
352       {
353         rstr += "|" + tmp;
354       }
355     }
356
357     if (_require_all)
358     {
359       if (!(_cflags & SEARCH_STRING)) // not match exact
360         rstr += WB + ".*";
361     }
362     else
363     {
364       rstr += ")";
365       if (_cflags & SEARCH_STRING) // match exact
366         rstr += "$";
367       else
368         rstr += WB + ".*";
369     }
370
371     return rstr;
372   }
373
374
375   PoolQuery::const_iterator PoolQuery::Impl::begin() const
376   {
377     compile();
378
379     // if only one repository has been specified, find it in the pool
380     sat::Pool pool(sat::Pool::instance());
381     sat::Pool::RepositoryIterator itr = pool.reposBegin();
382     if (!(_cflags & SEARCH_ALL_REPOS) && _repos.size() == 1)
383     {
384       string theone = *_repos.begin();
385       for (; itr->info().alias() != theone && itr != pool.reposEnd(); ++itr);
386       if (itr == pool.reposEnd())
387       {
388         RepoInfo info; info.setAlias(theone);
389         ERR << "Repository not found in sat pool." <<  endl;
390         ZYPP_THROW(repo::RepoNotFoundException(info));
391       }
392     }
393
394     DBG << "_cflags:" << _cflags << endl;
395
396     scoped_ptr< ::_Dataiterator> _rdit( new ::Dataiterator );
397     // needed while LookupAttr::iterator::dip_equal does ::memcmp:
398     ::memset( _rdit.get(), 0, sizeof(::_Dataiterator) );
399
400     if (_rcattrs.empty())
401     {
402     ::dataiterator_init(_rdit.get(),
403       _cflags & SEARCH_ALL_REPOS ? pool.get()->repos[0] : itr->get(), // repository \todo fix this
404       0,                                           // search all solvables
405       0,                                           // attribute id - only if 1 attr key specified
406       _rcstrings.empty() ? 0 : _rcstrings.c_str(), // compiled search string
407       _cflags);
408     }
409     else if (_rcattrs.size() == 1)
410     {
411       ::dataiterator_init(_rdit.get(),
412         _cflags & SEARCH_ALL_REPOS ? pool.get()->repos[0] : itr->get(), // repository \todo fix this 
413         0,                                           // search all solvables
414         _rcattrs.begin()->first.id(),                // keyname - attribute id - only if 1 attr key specified
415         _rcstrings.empty() ? 0 : _rcstrings.c_str(), // compiled search string 
416         _cflags);
417     }
418     else
419     {
420       ::dataiterator_init(_rdit.get(),
421         _cflags & SEARCH_ALL_REPOS ? pool.get()->repos[0] : itr->get(), /* repository - switch to next at the end of current one in increment() */ 
422         0, /*search all resolvables */
423         0, /*keyname - if only 1 attr key specified, pass it here, otherwise do more magic */
424         0, //qs.empty() ? 0 : qs.c_str(), /* create regex, pass it here */
425         _cflags);
426     }
427
428     if ((_cflags & SEARCH_STRINGMASK) == SEARCH_REGEX && _rdit->regex_err != 0)
429       ZYPP_THROW(Exception(str::form(
430           _("Invalid regular expression '%s': regcomp returned %d"),
431           _rcstrings.c_str(), _rdit->regex_err)));
432
433     PoolQuery::const_iterator it(_rdit, this);
434     it.increment();
435     return it;
436   }
437
438   PoolQuery::const_iterator PoolQuery::Impl::end() const
439   {
440     INT << "end" << endl;
441     return PoolQuery::const_iterator();
442   }
443
444
445   string PoolQuery::Impl::asString() const
446   {
447     ostringstream o;
448
449     o << "compiled: " << _compiled << endl;
450     
451     o << "kinds: ";
452     for(Kinds::const_iterator it = _kinds.begin();
453         it != _kinds.end(); ++it)
454       o << *it << " ";
455     o << endl;
456
457     o << "repos: ";
458     for(StrContainer::const_iterator it = _repos.begin();
459         it != _repos.end(); ++it)
460       o << *it << " ";
461     o << endl;
462
463     o << "string match flags:" << endl;
464     o << "* string/substring/glob/regex: " << (_cflags & SEARCH_STRINGMASK) << endl; 
465     o << "* SEARCH_NOCASE: " << ((_cflags & SEARCH_NOCASE) ? "yes" : "no") << endl;
466     o << "* SEARCH_ALL_REPOS: " << ((_cflags & SEARCH_ALL_REPOS) ? "yes" : "no") << endl;
467     o << "status filter flags:" << _status_flags << endl;
468
469     // raw
470
471     o << "strings: ";
472     for(StrContainer::const_iterator it = _strings.begin();
473         it != _strings.end(); ++it)
474       o << *it << " ";
475     o << endl;
476
477     o << "attributes: " << endl;
478     for(AttrMap::const_iterator ai = _attrs.begin(); ai != _attrs.end(); ++ai)
479     {
480       o << "* " << ai->first << ": ";
481       for(StrContainer::const_iterator vi = ai->second.begin();
482           vi != ai->second.end(); ++vi)
483         o << *vi << " ";
484       o << endl;
485     }
486
487     // compiled
488
489     o << "compiled strings: " << _rcstrings << endl;
490     o << "compiled attributes:" << endl;
491     for (CompiledAttrMap::const_iterator ai = _rcattrs.begin(); ai != _rcattrs.end(); ++ai)
492       o << "* " << ai->first << ": " << ai->second << endl;
493
494     return o.str();
495   }
496
497   /** \relates PoolQuery::Impl Stream output *//*
498   inline std::ostream & operator<<( std::ostream & str, const PoolQuery::Impl & obj )
499   {
500     return str << "PoolQuery::Impl";
501   }
502   */
503   ///////////////////////////////////////////////////////////////////
504
505   ///////////////////////////////////////////////////////////////////
506   namespace detail
507   { /////////////////////////////////////////////////////////////////
508
509   ///////////////////////////////////////////////////////////////////
510   //
511   //  CLASS NAME : PoolQuery::ResultIterator
512   //
513   ///////////////////////////////////////////////////////////////////
514
515   PoolQueryIterator::PoolQueryIterator()
516     : _sid(0), _has_next(false), _do_matching(false)
517   { this->base_reference() = LookupAttr::iterator(); }
518
519
520   PoolQueryIterator::PoolQueryIterator(
521       scoped_ptr< ::_Dataiterator> & dip_r,
522       const PoolQuery::Impl * pqimpl)
523   : _pqimpl(pqimpl)
524   , _sid(0)
525   , _has_next(true)
526   , _do_matching(_pqimpl->_rcattrs.size() > 1)
527   {
528     this->base_reference() = LookupAttr::iterator(dip_r, true); //!\todo pass chain_repos
529     _has_next = (*base_reference() != sat::detail::noId); 
530   }
531
532
533   PoolQueryIterator::PoolQueryIterator(const PoolQueryIterator & rhs)
534     : _pqimpl(rhs._pqimpl)
535     , _sid(rhs._sid)
536     , _has_next(rhs._has_next)
537     , _do_matching(rhs._do_matching)
538   { base_reference() = LookupAttr::iterator(rhs.base()); }
539
540
541   PoolQueryIterator::~PoolQueryIterator()
542   {}
543
544
545   PoolQueryIterator & PoolQueryIterator::operator=( const PoolQueryIterator & rhs )
546   {
547     base_reference() = rhs.base();
548     _pqimpl = rhs._pqimpl; //! \todo FIXME
549     _sid = rhs._sid;
550     _has_next = rhs._has_next;
551     _do_matching = rhs._do_matching;
552     return *this;
553   }
554
555
556   void PoolQueryIterator::increment()
557   {
558     if (!base().get())
559       return;
560
561     bool got_match = false;
562     if (_has_next)
563     {
564       DBG << "last: " << _sid << endl;
565       while (_has_next && !(got_match = matchSolvable()));
566     }
567
568     // no more solvables and the last did not match
569     if (!got_match && !_has_next)
570     {
571       base_reference() = LookupAttr::iterator();
572       _sid = 0;
573     }
574
575     DBG << "next: " << _sid << endl;
576   }
577
578   bool PoolQueryIterator::matchSolvable()
579   {
580     _sid = base().get()->solvid;
581
582     bool new_solvable = true;
583     bool matches = !_do_matching;
584     bool drop_by_kind_status = false;
585     bool drop_by_repo = false;
586     do
587     {
588       if (new_solvable)
589       {
590         while(1)
591         {
592           drop_by_repo = false;
593           if (!_pqimpl->_repos.empty() && 
594             _pqimpl->_repos.find(base().get()->repo->name) == _pqimpl->_repos.end())
595           {
596             drop_by_repo = true;
597             break;
598           }
599
600           drop_by_kind_status = false;
601
602           // whether to drop an uninstalled (repo) solvable
603           if ( (_pqimpl->_status_flags & PoolQuery::INSTALLED_ONLY) &&
604               base().get()->repo->name != sat::Pool::instance().systemRepoName() )
605           {
606             drop_by_kind_status = true;
607             break;
608           }
609
610           // whether to drop an installed (target) solvable
611           if ((_pqimpl->_status_flags & PoolQuery::UNINSTALLED_ONLY) &&
612               base().get()->repo->name == sat::Pool::instance().systemRepoName())
613           {
614             drop_by_kind_status = true;
615             break;
616           }
617
618           // whether to drop unwanted kind
619           if (!_pqimpl->_kinds.empty())
620           {
621             sat::Solvable s(_sid);
622             // the user wants to filter by kind.
623             if (_pqimpl->_kinds.find(s.kind()) == _pqimpl->_kinds.end())
624               drop_by_kind_status = true;
625           }
626
627           break;
628         }
629
630         matches = matches && !drop_by_kind_status && !drop_by_repo;
631       }
632
633       if (_do_matching && !drop_by_kind_status)
634       {
635         if (!matches)
636         {
637           SolvAttr attr(base().get()->key->name);
638           PoolQuery::CompiledAttrMap::const_iterator ai = _pqimpl->_rcattrs.find(attr);
639           if (ai != _pqimpl->_rcattrs.end())
640           {
641             if ((_pqimpl->_cflags & SEARCH_STRINGMASK) == SEARCH_REGEX)
642             {
643               const regex_t * regex;
644               if (_pqimpl->_rcstrings.empty())
645               {
646                 map<sat::SolvAttr, regex_t>::const_iterator rai = _pqimpl->_rattrs.find(attr);
647                 if (rai != _pqimpl->_rattrs.end())
648                   regex = &rai->second;
649                 else
650                 {
651                   ERR << "no compiled regex found for " <<  attr << endl;
652                   continue;
653                 }
654               }
655               else
656                 regex = &_pqimpl->_regex;
657               matches = ::dataiterator_match(base().get(), _pqimpl->_cflags, regex);
658             }
659             else
660             {
661               const string & sstr =
662                 _pqimpl->_rcstrings.empty() ? ai->second : _pqimpl->_rcstrings;
663               matches = ::dataiterator_match(base().get(), _pqimpl->_cflags, sstr.c_str());
664             }
665
666 //            if (matches)
667               /* After calling dataiterator_match (with any string matcher set)
668                  the kv.str member will be filled with something sensible.  */
669   /*            INT << "value: " << base().get()->kv.str << endl
670                   << " mstr: " <<  sstr << endl;*/ 
671           }
672         }
673       }
674
675       if (drop_by_repo)
676       {
677         base_reference().nextSkipRepo();
678         drop_by_repo = false;
679       }
680       else if (drop_by_kind_status)
681       {
682         base_reference().nextSkipSolvable();
683         drop_by_kind_status = false;
684       }
685
686       // copy the iterator to forward check for the next attribute ***
687       _tmpit = base_reference();
688       _has_next = (*(++_tmpit) != sat::detail::noId);
689
690       if (_has_next)
691       {
692         // *** now increment. Had it not be done this way,
693         // the LookupAttr::iterator could have reached the end() while
694         // trying to reach a matching attribute or the next solvable
695         // thus resulting to a problem in the equal() method
696         ++base_reference();
697         new_solvable = base().get()->solvid != _sid;
698       }
699       // no more attributes in this repo, return
700       else
701         return matches; // did the last solvable match conditions?
702     }
703     while (!new_solvable);
704
705     return matches;
706   }
707
708   ///////////////////////////////////////////////////////////////////
709   } //namespace detail
710   ///////////////////////////////////////////////////////////////////
711
712   ///////////////////////////////////////////////////////////////////
713   //
714   //    CLASS NAME : PoolQuery
715   //
716   ///////////////////////////////////////////////////////////////////
717
718   PoolQuery::PoolQuery()
719     : _pimpl(new Impl())
720   {}
721
722
723   PoolQuery::~PoolQuery()
724   {}
725
726
727   void PoolQuery::addRepo(const std::string &repoalias)
728   {
729     _pimpl->_repos.insert(repoalias);
730     _pimpl->_flags &= ~SEARCH_ALL_REPOS;
731   }
732
733
734   void PoolQuery::addKind(const Resolvable::Kind &kind)
735   { _pimpl->_kinds.insert(kind); }
736
737
738   void PoolQuery::addString(const string & value)
739   { _pimpl->_strings.insert(value); }
740
741
742   void PoolQuery::addAttribute(const sat::SolvAttr & attr, const std::string & value)
743   { _pimpl->_attrs[attr].insert(value); }
744
745
746   void PoolQuery::setCaseSensitive(const bool value)
747   {
748     if (value)
749       _pimpl->_flags &= ~SEARCH_NOCASE;
750     else
751       _pimpl->_flags |= SEARCH_NOCASE;
752   }
753
754
755   void PoolQuery::setMatchSubstring()
756   { _pimpl->_flags = (_pimpl->_flags & ~SEARCH_STRINGMASK) | SEARCH_SUBSTRING; }
757   void PoolQuery::setMatchExact()
758   { _pimpl->_flags = (_pimpl->_flags & ~SEARCH_STRINGMASK) | SEARCH_STRING; }
759   void PoolQuery::setMatchRegex()
760   { _pimpl->_flags = (_pimpl->_flags & ~SEARCH_STRINGMASK) | SEARCH_REGEX; }
761   void PoolQuery::setMatchGlob()
762   { _pimpl->_flags = (_pimpl->_flags & ~SEARCH_STRINGMASK) | SEARCH_GLOB; }
763   void PoolQuery::setMatchWord()
764   {
765     _pimpl->_match_word = true;
766     _pimpl->_flags = (_pimpl->_flags & ~SEARCH_STRINGMASK) | SEARCH_REGEX;
767   }
768
769   void PoolQuery::setFlags(int flags)
770   { _pimpl->_flags = flags; }
771
772
773   void PoolQuery::setInstalledOnly()
774   { _pimpl->_status_flags = INSTALLED_ONLY; }
775   void PoolQuery::setUninstalledOnly()
776   { _pimpl->_status_flags = UNINSTALLED_ONLY; }
777   void PoolQuery::setStatusFilterFlags( PoolQuery::StatusFilter flags )
778   { _pimpl->_status_flags = flags; }
779
780
781   void PoolQuery::setRequireAll(const bool require_all)
782   { _pimpl->_require_all = require_all; }
783
784
785   const PoolQuery::StrContainer &
786   PoolQuery::strings() const
787   { return _pimpl->_strings; }
788
789   const PoolQuery::AttrMap &
790   PoolQuery::attributes() const
791   { return _pimpl->_attrs; }
792
793   const PoolQuery::Kinds &
794   PoolQuery::kinds() const
795   { return _pimpl->_kinds; }
796
797   const PoolQuery::StrContainer &
798   PoolQuery::repos() const
799   { return _pimpl->_repos; }
800
801   bool PoolQuery::caseSensitive() const
802   { return _pimpl->_flags & SEARCH_NOCASE; }
803
804   bool PoolQuery::matchExact() const
805   { return (_pimpl->_flags & SEARCH_STRINGMASK) == SEARCH_STRING; }
806   bool PoolQuery::matchSubstring() const
807   { return (_pimpl->_flags & SEARCH_STRINGMASK) == SEARCH_SUBSTRING; }
808   bool PoolQuery::matchGlob() const
809   { return (_pimpl->_flags & SEARCH_STRINGMASK) == SEARCH_GLOB; }
810   bool PoolQuery::matchRegex() const
811   { return (_pimpl->_flags & SEARCH_STRINGMASK) == SEARCH_REGEX; }
812   int PoolQuery::matchType() const
813   { return _pimpl->_flags & SEARCH_STRINGMASK; }
814
815   bool PoolQuery::matchWord() const
816   { return _pimpl->_match_word; }
817
818   bool PoolQuery::requireAll() const
819   { return _pimpl->_require_all; }
820
821   PoolQuery::StatusFilter PoolQuery::statusFilterFlags() const
822   { return _pimpl->_status_flags; }
823
824   PoolQuery::const_iterator PoolQuery::begin() const
825   { return _pimpl->begin(); }
826
827
828   PoolQuery::const_iterator PoolQuery::end() const
829   { return _pimpl->end(); }
830
831
832   bool PoolQuery::empty()
833   { return _pimpl->begin() == _pimpl->end(); }
834
835   //! \todo collect the result, reuse if not dirty
836   PoolQuery::size_type PoolQuery::size()
837   {
838     size_type count = 0;
839     for(const_iterator it = _pimpl->begin(); it != _pimpl->end(); ++it, ++count);
840     return count;
841   }
842
843
844   void PoolQuery::execute(ProcessResolvable fnc)
845   { invokeOnEach(_pimpl->begin(), _pimpl->end(), fnc); }
846
847
848   ///////////////////////////////////////////////////////////////////
849   //
850   //  CLASS NAME : PoolQuery::Attr
851   //
852   /**
853    * represents all atributes in PoolQuery except SolvAtributes, which are
854    * used as is (not needed extend anything if someone adds new solv attr)
855    */
856   struct PoolQueryAttr : public IdStringType<PoolQueryAttr>
857   {
858     private:
859       friend class IdStringType<PoolQueryAttr>;
860       IdString _str;
861     public:
862     
863     //noAttr
864     PoolQueryAttr(){}
865
866     explicit PoolQueryAttr( const char* cstr_r )
867         : _str( cstr_r )
868       {}
869
870     explicit PoolQueryAttr( const std::string & str_r )
871         : _str( str_r )
872       {}
873
874     //unknown atributes
875     static const PoolQueryAttr noAttr;
876
877     // own attributes
878     static const PoolQueryAttr repoAttr;
879     static const PoolQueryAttr kindAttr;
880     static const PoolQueryAttr stringAttr;
881     static const PoolQueryAttr stringTypeAttr;
882     static const PoolQueryAttr requireAllAttr;
883     static const PoolQueryAttr caseSensitiveAttr;
884     static const PoolQueryAttr installStatusAttr;
885   };
886
887   const PoolQueryAttr PoolQueryAttr::noAttr;
888
889   const PoolQueryAttr PoolQueryAttr::repoAttr( "repo" );
890   const PoolQueryAttr PoolQueryAttr::kindAttr( "kind" );
891   const PoolQueryAttr PoolQueryAttr::stringAttr( "global_string" );
892   const PoolQueryAttr PoolQueryAttr::stringTypeAttr("string_type");
893   const PoolQueryAttr PoolQueryAttr::requireAllAttr("require_all");
894   const PoolQueryAttr PoolQueryAttr::caseSensitiveAttr("case_sensitive");
895   const PoolQueryAttr PoolQueryAttr::installStatusAttr("install_status");
896
897   class StringTypeAttr : public IdStringType<PoolQueryAttr>
898   {
899     friend class IdStringType<StringTypeAttr>;
900     IdString _str;
901
902   public:
903     StringTypeAttr(){}
904     explicit StringTypeAttr( const char* cstr_r )
905             : _str( cstr_r ){}
906     explicit StringTypeAttr( const std::string & str_r )
907              : _str( str_r ){}
908
909     static const StringTypeAttr noAttr;
910
911     static const StringTypeAttr exactAttr;
912     static const StringTypeAttr substringAttr;
913     static const StringTypeAttr regexAttr;
914     static const StringTypeAttr globAttr;
915     static const StringTypeAttr wordAttr;
916   };
917     const StringTypeAttr StringTypeAttr::noAttr;
918
919     const StringTypeAttr StringTypeAttr::exactAttr("exact");
920     const StringTypeAttr StringTypeAttr::substringAttr("substring");
921     const StringTypeAttr StringTypeAttr::regexAttr("regex");
922     const StringTypeAttr StringTypeAttr::globAttr("glob");
923     const StringTypeAttr StringTypeAttr::wordAttr("word");
924
925   ///////////////////////////////////////////////////////////////////
926
927
928   //\TODO maybe ctor with stream can be usefull
929   bool PoolQuery::recover( istream &str, char delim )
930   {
931     bool finded_something = false; //indicates some atributes is finded
932     string s;
933     do {
934       if ( str.eof() )
935         break;
936
937       getline( str, s, delim );
938
939       if ((!s.empty()) && s[0]=='#') //comment
940       {
941         continue;
942       }
943
944       string::size_type pos = s.find(':');
945       if (s.empty() || pos == s.npos) // some garbage on line... act like blank line
946       {
947         if (finded_something) //is first blank line after record?
948         {
949           break;
950         }
951         else
952         {
953           continue;
954         }
955       }
956
957       finded_something = true;
958
959       string attrName(str::trim(string(s,0,pos))); // trimmed name of atribute
960       string attrValue(str::trim(string(s,pos+1,s.npos))); //trimmed value
961
962       PoolQueryAttr attribute( attrName );
963
964       if ( attribute==PoolQueryAttr::repoAttr )
965       {
966         addRepo( attrValue );
967       }
968       else if ( attribute==PoolQueryAttr::kindAttr )
969       {
970         addKind( Resolvable::Kind(attrValue) );
971       }
972       else if ( attribute==PoolQueryAttr::stringAttr )
973       {
974         addString( attrValue );
975       }
976       else if ( attribute==PoolQueryAttr::stringTypeAttr )
977       {
978         StringTypeAttr s(attrValue);
979         if( s == StringTypeAttr::regexAttr )
980         {
981           setMatchRegex();
982         }
983         else if ( s == StringTypeAttr::globAttr )
984         {
985           setMatchGlob();
986         }
987         else if ( s == StringTypeAttr::exactAttr )
988         {
989           setMatchExact();
990         }
991         else if ( s == StringTypeAttr::substringAttr )
992         {
993           setMatchSubstring();
994         }
995         else if ( s == StringTypeAttr::wordAttr )
996         {
997           setMatchWord();
998         }
999         else if ( s == StringTypeAttr::noAttr )
1000         {
1001           WAR << "unknown string type " << attrValue << endl;
1002         }
1003         else
1004         {
1005           WAR << "forget recover some attribute defined as String type attribute: " << attrValue << endl;
1006         }
1007       }
1008       else if ( attribute==PoolQueryAttr::requireAllAttr )
1009       {
1010         if ( str::strToTrue(attrValue) )
1011         {
1012           setRequireAll(true);
1013         }
1014         else if ( !str::strToFalse(attrValue) )
1015         {
1016           setRequireAll(false);
1017         }
1018         else
1019         {
1020           WAR << "unknown boolean value " << attrValue << endl;
1021         }
1022       }
1023       else if ( attribute==PoolQueryAttr::caseSensitiveAttr )
1024       {
1025         if ( str::strToTrue(attrValue) )
1026         {
1027           setCaseSensitive(true);
1028         }
1029         else if ( !str::strToFalse(attrValue) )
1030         {
1031           setCaseSensitive(false);
1032         }
1033         else
1034         {
1035           WAR << "unknown boolean value " << attrValue << endl;
1036         }
1037       }
1038       else if ( attribute==PoolQueryAttr::installStatusAttr )
1039       {
1040         if( attrValue == "all" )
1041         {
1042           setStatusFilterFlags( ALL );
1043         }
1044         else if( attrValue == "installed" )
1045         {
1046           setInstalledOnly();
1047         }
1048         else if( attrValue == "not-installed" )
1049         {
1050           setUninstalledOnly();
1051         }
1052         else
1053         {
1054           WAR << "Unknown value for install status " << attrValue << endl;
1055         }
1056       }
1057       else if ( attribute==PoolQueryAttr::noAttr )
1058       {
1059         WAR << "empty attribute name" << endl;
1060       }
1061       else
1062       {
1063         string s = attrName;
1064         boost::replace_all( s,"_",":" );
1065         SolvAttr a(s);
1066         addAttribute(a,attrValue);
1067       }
1068       
1069     } while ( true );
1070
1071     return finded_something;
1072   }
1073
1074   void PoolQuery::serialize( ostream &str, char delim ) const
1075   {
1076     //separating delim
1077     str << delim; 
1078     //iterate thrue all settings and write it
1079     static const zypp::PoolQuery q; //not save default options, so create default query example
1080     
1081     for_( it, repos().begin(), repos().end() )
1082     {
1083       str << "repo: " << *it << delim ;
1084     }
1085
1086     for_( it, kinds().begin(), kinds().end() )
1087     {
1088       str << "kind: " << it->idStr() << delim ;
1089     }
1090
1091     if (matchType()!=q.matchType())
1092     {
1093       switch( matchType() )
1094       {
1095       case SEARCH_STRING:
1096         str << "string_type: exact" << delim;
1097         break;
1098       case SEARCH_SUBSTRING:
1099         str << "string_type: substring" << delim;
1100         break;
1101       case SEARCH_GLOB:
1102         str << "string_type: glob" << delim;
1103         break;
1104       case SEARCH_REGEX:
1105         str << "string_type: regex" << delim;
1106         break;
1107       default:
1108         WAR << "unknown match type "  << matchType() << endl;
1109       }
1110     }
1111
1112     if( caseSensitive() != q.caseSensitive() )
1113     {
1114       str << "case_sensitive: ";
1115       if (caseSensitive())
1116       {
1117         str << "on" << delim;
1118       }
1119       else 
1120       {
1121         str << "off" << delim;
1122       }
1123     }
1124
1125     if( requireAll() != q.requireAll() )
1126     {
1127       str << "require_all: ";
1128       if (requireAll())
1129       {
1130         str << "on" << delim;
1131       }
1132       else 
1133       {
1134         str << "off" << delim;
1135       }
1136     }
1137
1138     if( statusFilterFlags() != q.statusFilterFlags() )
1139     {
1140       switch( statusFilterFlags() )
1141       {
1142       case ALL:
1143         str << "install_status: all" << delim;
1144         break;
1145       case INSTALLED_ONLY:
1146         str << "install_status: installed" << delim;
1147         break;
1148       case UNINSTALLED_ONLY:
1149         str << "install_status: not-installed" << delim;
1150         break;
1151       }
1152     }
1153
1154     for_( it, strings().begin(), strings().end() )
1155     {
1156       str << "global_string: " << *it << delim;
1157     }
1158
1159     for_( it, attributes().begin(), attributes().end() )
1160     {
1161       string s = it->first.asString();
1162       boost::replace_all(s,":","_"); 
1163       for_( it2,it->second.begin(),it->second.end() )
1164       {
1165         str << s <<": "<< *it2 << delim;
1166       }
1167     }
1168
1169     //separating delim - protection
1170     str << delim; 
1171
1172   }
1173
1174
1175   string PoolQuery::asString() const
1176   { return _pimpl->asString(); }
1177
1178
1179   ostream & operator<<( ostream & str, const PoolQuery & obj )
1180   { return str << obj.asString(); }
1181
1182   //internal matching two containers O(n^2)
1183   template <class Container>
1184   bool equalContainers(const Container& a, const Container& b)
1185   {
1186     if (a.size()!=b.size())
1187       return false;
1188
1189     for_(it,a.begin(),a.end())
1190     {
1191       bool finded = false;
1192       for_( it2, b.begin(),b.end() )
1193       {
1194         if (*it==*it2)
1195         {
1196           finded = true;
1197           break;
1198         }
1199       }
1200
1201       if (!finded)
1202         return false;
1203     }
1204     return true;
1205   }
1206
1207   bool PoolQuery::operator==(const PoolQuery& a) const
1208   {
1209     if (!_pimpl->_compiled)
1210       _pimpl->compile();
1211     if (!a._pimpl->_compiled)
1212       a._pimpl->compile();
1213     if( matchType()!=a.matchType() )
1214       return false;
1215     if( a.matchWord()!=matchWord())
1216       return false;
1217     if( a.requireAll()!=requireAll() )
1218       return false;
1219     if(!equalContainers(a.kinds(), kinds()))
1220       return false;
1221     if(!equalContainers(a.repos(), repos()))
1222       return false;
1223     if(a._pimpl->_rcstrings!=_pimpl->_rcstrings)
1224       return false;
1225     if(!equalContainers(a._pimpl->_rcattrs, _pimpl->_rcattrs))
1226       return false;
1227     if(a._pimpl->_cflags!= _pimpl->_cflags)
1228       return false;
1229
1230     return true;
1231   }
1232
1233
1234   /////////////////////////////////////////////////////////////////
1235 } // namespace zypp
1236 ///////////////////////////////////////////////////////////////////
1237