Imported Upstream version 17.23.7
[platform/upstream/libzypp.git] / tools / zypp-NameReqPrv.cc
1 #define INCLUDE_TESTSETUP_WITHOUT_BOOST
2 #include "../tests/lib/TestSetup.h"
3 #undef  INCLUDE_TESTSETUP_WITHOUT_BOOST
4
5 #include <algorithm>
6 #include <zypp/PoolQuery.h>
7 #include <zypp/ResObjects.h>
8 #include <zypp/ui/SelectableTraits.h>
9
10 static std::string appname( "NameReqPrv" );
11
12 #define message cout
13 using std::flush;
14
15 int errexit( const std::string & msg_r = std::string(), int exit_r = 100 )
16 {
17   if ( ! msg_r.empty() )
18   {
19     cerr << endl << msg_r << endl << endl;
20   }
21   return exit_r;
22 }
23
24 int usage( const std::string & msg_r = std::string(), int exit_r = 100 )
25 {
26   if ( ! msg_r.empty() )
27   {
28     cerr << endl << msg_r << endl << endl;
29   }
30   cerr << "Usage: " << appname << " [--root ROOTDIR] [OPTIONS] NAME... [[OPTIONS] NAME...]..." << endl;
31   cerr << "  Load all enabled repositories (no refresh) and search for" << endl;
32   cerr << "  occurrences of NAME (regex or -x) in package names or dependencies" << endl;
33   cerr << "  --root   Load repos from the system located below ROOTDIR. If ROOTDIR" << endl;
34   cerr << "           denotes a sover testcase, the testcase is loaded." << endl;
35   cerr << "  --installed Process installed packages only." << endl;
36   cerr << "  -i/-I    turn on/off case insensitive search (default on)" << endl;
37   cerr << "  -n/-N    turn on/off looking for names       (default on)" << endl;
38   cerr << "  -p/-P    turn on/off looking for provides    (default off)" << endl;
39   cerr << "  -r/-R    turn on/off looking for requires    (default off)" << endl;
40   cerr << "  -c/-C    turn on/off looking for conflicts   (default off)" << endl;
41   cerr << "  -o/-O    turn on/off looking for obsoletes   (default off)" << endl;
42   cerr << "  -m/-M    turn on/off looking for recommends  (default off)" << endl;
43   cerr << "  -s/-S    turn on/off looking for supplements (default off)" << endl;
44   cerr << "  -e/-E    turn on/off looking for enhan./sugg.(default off)" << endl;
45   cerr << "  -a       short for -n -p -r" << endl;
46   cerr << "  -A       short for -n -P -R" << endl;
47   cerr << "  -x       do exact matching (glob) rather than regex (substring)" << endl;
48   cerr << "  -D <pkg> dump dependencies of <pkg>" << endl;
49   cerr << "" << endl;
50   return exit_r;
51 }
52
53 #define COL_R   "\033[0;31m"
54 #define COL_G   "\033[0;32m"
55 #define COL_B   "\033[0;34m"
56 #define COL_C   "\033[0;36m"
57 #define COL_M   "\033[0;35m"
58 #define COL_Y   "\033[0;33m"
59 #define COL_BL  "\033[0;30m"
60 #define COL_WH  "\033[1;37m"
61 #define COL_OFF "\033[0m"
62
63 struct PQSort
64 {
65   // std::less semantic
66   bool operator()( const sat::Solvable & lhs, const sat::Solvable & rhs ) const
67   {
68     {
69       bool l = lhs.isSystem();
70       bool r = rhs.isSystem();
71       if ( l != r )
72         return r;
73     }
74     {
75       IdString l { lhs.ident() };
76       IdString r { rhs.ident() };
77       if ( l != r )
78         return l < r;
79     }
80     return avo( PoolItem(lhs), PoolItem(rhs) );
81     return lhs.id() > rhs.id();
82   }
83
84   ui::SelectableTraits::AVOrder avo;
85 };
86
87 struct Table
88 {
89   std::vector<std::string> & row( const sat::Solvable & solv_r )
90   {
91     //smax( _maxSID,  );
92     smax( _maxNAME, solv_r.ident().size() + solv_r.edition().size() + solv_r.arch().size() );
93     smax( _maxREPO, solv_r.repository().name().size(), solv_r.repository().name() );
94     //smax( _maxTIME, );
95     //smax( _maxVEND, solv_r.vendor().size() );
96     return _map[solv_r];
97   }
98
99   void row( PoolQuery::const_iterator it_r )
100   {
101     std::vector<std::string> & details { row( *it_r ) };
102     for_( match, it_r.matchesBegin(), it_r.matchesEnd() ) {
103       details.push_back( match->inSolvAttr().asString().substr( 9, 3 )+": " +match->asString() );
104     }
105   }
106
107   std::ostream & dumpOn( std::ostream & str ) const
108   {
109     #define S "  "
110
111     #define fmtSID  "%*d"
112     #define argSID  _maxSID, slv.id()
113
114     #define fmtNAME COL_B "%s" COL_OFF "-" COL_G "%s" COL_OFF ".%-*s"
115     #define argNAME slv.ident().c_str(), slv.edition().c_str(), _maxNAME-slv.ident().size()-slv.edition().size(), slv.arch().c_str()
116
117     #define fmtREPO "(%2d)%-*s"
118     #define argREPO slv.repository().info().priority(), _maxREPO, slv.repository().name().c_str()
119
120     #define fmtTIME "%10ld"
121     #define argTIME time_t( slv.isSystem() ? slv.installtime() : slv.buildtime() )
122
123     #define fmtVEND "%s"
124     #define argVEND slv.vendor().c_str()
125
126     std::string dind( _maxSID + _maxNAME+2/*-.*/ + 2*strlen(S), ' ' );
127
128     for ( const auto & el : _map ) {
129       sat::Solvable slv { el.first };
130       const char * tagCol = slv.isSystem() ? COL_M : ui::Selectable::get(slv)->identicalInstalled(PoolItem(slv)) ? COL_C : "";
131
132       str << str::form( "%s"    fmtSID S fmtNAME S "%s"    fmtREPO S fmtTIME S fmtVEND COL_OFF "\n",
133                         tagCol, argSID,  argNAME,  tagCol, argREPO,  argTIME,  argVEND );
134
135       for ( const auto & d : el.second )
136         str << dind << d << endl;
137     }
138     return str;
139   }
140
141 private:
142   static void smax( unsigned & var_r, unsigned val_r, std::string_view n = {} )
143   { if ( val_r > var_r ) var_r = val_r; }
144
145 private:
146   unsigned _maxSID  = 7;        // size + indent
147   unsigned _maxNAME = 0;
148   unsigned _maxREPO = 0;
149   //unsigned _maxTIME = 10;
150   //unsigned _maxVEND = 0;
151   std::map<sat::Solvable, std::vector<std::string>, PQSort> _map;
152 };
153
154 inline std::ostream & operator<<( std::ostream & str, const Table & table_r )
155 { return table_r.dumpOn( str ); }
156
157 ///////////////////////////////////////////////////////////////////
158
159 void dDump( const std::string & spec_r )
160 {
161   message << "DUMP " << spec_r << " {";
162
163   sat::WhatProvides q( Capability::guessPackageSpec( spec_r ) );
164   if ( q.empty() )
165   {
166     message << "}" << endl;
167     return;
168   }
169
170   for ( const auto & el : q )
171   {
172     message << endl << "==============================" << endl << dump(el);
173     if ( isKind<Product>(el) )
174     {
175       message << endl << "REPLACES: " << make<Product>(el)->replacedProducts();
176     }
177     else if ( isKind<Pattern>(el) )
178     {
179       message << endl << "CONTENT: " << make<Pattern>(el)->contents();
180     }
181     else if ( isKind<Patch>(el) )
182     {
183       message << endl << "STATUS: " << PoolItem(el);
184     }
185   }
186   message << endl << "}" << endl;
187 }
188
189 ///////////////////////////////////////////////////////////////////
190
191 void dTree( const std::string & cmd_r, const std::string & spec_r )
192 {
193   message << "tree " << spec_r << " {";
194
195   sat::WhatProvides spec( Capability::guessPackageSpec( spec_r ) );
196   if ( spec.empty() )
197   {
198     message << "}" << endl;
199     return;
200   }
201
202   static const std::list<sat::SolvAttr> attrs {
203     sat::SolvAttr::requires,
204     sat::SolvAttr::recommends,
205     sat::SolvAttr::obsoletes,
206     sat::SolvAttr::conflicts,
207     sat::SolvAttr::supplements,
208   };
209
210   std::map<sat::SolvAttr,std::map<sat::Solvable,std::set<std::string>>> result; // solvables recommending provided capability
211   {
212     Table t;
213     for ( const auto & el : spec )
214     {
215       auto & details { t.row( el ) };
216       for ( const auto & cap : el.provides() )
217       {
218         //details.push_back( "prv: "+cap.asString() );  // list only matching ones
219
220         // get attrs matching cap
221         for ( const auto & attr : attrs )
222         {
223           PoolQuery q;
224           q.addDependency( attr, cap );
225           if ( q.empty() )
226             continue;
227           for_( it, q.begin(), q.end() ) {
228             for_( match, it.matchesBegin(), it.matchesEnd() ) {
229               result[attr][*it].insert( match->inSolvAttr().asString().substr( 9, 3 )+": " +match->asString()
230               + " (" + cap.asString() + ")"
231               );
232             }
233           }
234         }
235       }
236     }
237     message << endl << t;
238   }
239
240   for ( const auto & attr : attrs )
241   {
242     if ( result[attr].empty() )
243       continue;
244
245     message << endl << "======== " << attr << " by:" << endl;
246     Table t;
247     for ( const auto & el : result[attr] )
248     {
249       auto & details { t.row( el.first ) };
250       for ( const auto & cap : el.second )
251         details.push_back( cap );
252     }
253     message << endl << t << endl;
254   }
255   message << "}" << endl;
256 }
257
258 /******************************************************************
259 **
260 **      FUNCTION NAME : main
261 **      FUNCTION TYPE : int
262 */
263 int main( int argc, char * argv[] )
264 {
265   INT << "===[START]==========================================" << endl;
266   appname = Pathname::basename( argv[0] );
267   --argc,++argv;
268
269   if ( ! argc )
270   {
271     return usage();
272   }
273
274   ///////////////////////////////////////////////////////////////////
275
276   ZConfig::instance();
277   Pathname sysRoot("/");
278   sat::Pool satpool( sat::Pool::instance() );
279
280   if ( argc && (*argv) == std::string("--root") )
281   {
282     --argc,++argv;
283     if ( ! argc )
284       return errexit("--root requires an argument.");
285
286     if ( ! PathInfo( *argv ).isDir() )
287       return errexit("--root requires a directory.");
288
289     sysRoot = *argv;
290     --argc,++argv;
291   }
292
293   bool onlyInstalled( false );
294   if ( argc && (*argv) == std::string("--installed") )
295   {
296     --argc,++argv;
297     onlyInstalled = true;
298   }
299
300   if ( TestSetup::isTestcase( sysRoot ) )
301   {
302     message << str::form( "*** Load Testcase from '%s'", sysRoot.c_str() ) << endl;
303     TestSetup test;
304     test.loadTestcaseRepos( sysRoot );
305     dumpRange( message, satpool.reposBegin(), satpool.reposEnd() ) << endl;
306   }
307   else if ( TestSetup::isTestSetup( sysRoot ) )
308   {
309     message << str::form( "*** Load TestSetup from '%s'", sysRoot.c_str() ) << endl;
310     const char * astr = getenv( "ZYPP_TESTSUITE_FAKE_ARCH" );
311     if ( !astr || !*astr )
312       astr = getenv( "ZYPP_ARCH" );
313     if ( !astr || !*astr )
314       astr = "x86_64";
315     TestSetup test( sysRoot, Arch( astr ) );
316     test.loadRepos();
317     dumpRange( message, satpool.reposBegin(), satpool.reposEnd() ) << endl;
318   }
319   else
320   {
321     // a system
322     message << str::form( "*** Load system at '%s'", sysRoot.c_str() ) << endl;
323     if ( true )
324     {
325       message << "*** load target '" << Repository::systemRepoAlias() << "'\t" << endl;
326       getZYpp()->initializeTarget( sysRoot );
327       getZYpp()->target()->load();
328       message << satpool.systemRepo() << endl;
329     }
330
331     if ( !onlyInstalled )
332     {
333       RepoManager repoManager( sysRoot );
334       RepoInfoList repos = repoManager.knownRepositories();
335       for_( it, repos.begin(), repos.end() )
336       {
337         RepoInfo & nrepo( *it );
338
339         if ( ! nrepo.enabled() )
340           continue;
341
342         if ( ! repoManager.isCached( nrepo ) )
343         {
344           message << str::form( "*** omit uncached repo '%s' (do 'zypper refresh')", nrepo.name().c_str() ) << endl;
345           continue;
346         }
347
348         message << str::form( "*** load repo '%s'\t", nrepo.name().c_str() ) << flush;
349         try
350         {
351           repoManager.loadFromCache( nrepo );
352           message << satpool.reposFind( nrepo.alias() ) << endl;
353         }
354         catch ( const Exception & exp )
355         {
356           message << exp.asString() + "\n" + exp.historyAsString() << endl;
357           message << str::form( "*** omit broken repo '%s' (do 'zypper refresh')", nrepo.name().c_str() ) << endl;
358           continue;
359         }
360       }
361     }
362   }
363   ///////////////////////////////////////////////////////////////////
364
365   bool ignorecase       ( true );
366   bool matechexact      ( false );
367   bool withSrcPackages  ( false );
368   bool names            ( true );
369   bool provides         ( false );
370   bool requires         ( false );
371   bool conflicts        ( false );
372   bool obsoletes        ( false );
373   bool recommends       ( false );
374   bool supplements      ( false );
375   bool enhacements      ( false );
376
377
378   for ( ; argc; --argc,++argv )
379   {
380     if ( (*argv)[0] == '-' )
381     {
382       for ( const char * arg = (*argv)+1; *arg != '\0'; ++arg ) // -pr for -p -r
383       {
384         switch ( *arg )
385         {
386           case 'a': names =             true,   requires = provides =   true;   break;
387           case 'A': names =             true,   requires = provides =   false;  break;
388           case 'D':
389             if ( argc > 1 )
390             {
391               --argc,++argv;
392               dDump( *argv );
393             }
394             else
395               return errexit("-D <pkgspec> requires an argument.");
396             break;
397           case 'T':
398             if ( argc > 1 )
399             {
400               std::string cmd { *argv };
401               --argc,++argv;
402               dTree( cmd, *argv );
403             }
404             else
405               return errexit("-T <pkgspec> requires an argument.");
406             break;
407           case 'i': ignorecase =        true;   break;
408           case 'I': ignorecase =        false;  break;
409           case 'x': matechexact =       true;   break;
410           case 'n': names =             true;   break;
411           case 'N': names =             false;  break;
412           case 'r': requires =          true;   break;
413           case 'R': requires =          false;  break;
414           case 'p': provides =          true;   break;
415           case 'P': provides =          false;  break;
416           case 'c': conflicts =         true;   break;
417           case 'C': conflicts =         false;  break;
418           case 'o': obsoletes =         true;   break;
419           case 'O': obsoletes =         false;  break;
420           case 'm': recommends =        true;   break;
421           case 'M': recommends =        false;  break;
422           case 's': supplements =       true;   break;
423           case 'S': supplements =       false;  break;
424           case 'e': enhacements =       true;   break;
425           case 'E': enhacements =       false;  break;
426         }
427       }
428       continue;
429     }
430
431     PoolQuery q;
432     if ( onlyInstalled )
433       q.setInstalledOnly();
434     std::string qstr( *argv );
435
436     if ( *argv == ResKind::product )
437     {
438       q.addKind( ResKind::product );
439     }
440     else if ( *argv == ResKind::patch )
441     {
442       q.addKind( ResKind::patch );
443     }
444     else if ( *argv == ResKind::pattern )
445     {
446       q.addKind( ResKind::pattern );
447     }
448     else
449     {
450       sat::Solvable::SplitIdent ident( qstr );
451       if ( ident.kind() != ResKind::package )
452       {
453         q.addKind( ident.kind() );
454         q.addString( ident.name().asString() );
455       }
456       else
457         q.addString( qstr );
458
459       if ( matechexact )
460         q.setMatchGlob();
461       else
462         q.setMatchRegex();
463       q.setCaseSensitive( ! ignorecase );
464
465       if ( names )
466         q.addAttribute( sat::SolvAttr::name );
467       if ( provides )
468       {
469         q.addDependency( sat::SolvAttr::provides );
470         q.addDependency( sat::SolvAttr::provides, Capability(qstr) );
471       }
472       if ( requires )
473       {
474         q.addDependency( sat::SolvAttr::requires );
475         q.addDependency( sat::SolvAttr::requires, Capability(qstr) );
476       }
477       if ( conflicts )
478       {
479         q.addDependency( sat::SolvAttr::conflicts );
480         q.addDependency( sat::SolvAttr::conflicts, Capability(qstr) );
481       }
482       if ( obsoletes )
483       {
484         q.addDependency( sat::SolvAttr::obsoletes );
485         q.addDependency( sat::SolvAttr::obsoletes, Capability(qstr) );
486       }
487       if ( recommends )
488       {
489         q.addDependency( sat::SolvAttr::recommends );
490         q.addDependency( sat::SolvAttr::recommends, Capability(qstr) );
491       }
492       if ( supplements )
493       {
494         q.addDependency( sat::SolvAttr::supplements );
495         q.addDependency( sat::SolvAttr::supplements, Capability(qstr) );
496       }
497       if ( enhacements )
498       {
499         q.addDependency( sat::SolvAttr::enhances );
500         q.addDependency( sat::SolvAttr::enhances, Capability(qstr) );
501         q.addDependency( sat::SolvAttr::suggests );
502         q.addDependency( sat::SolvAttr::suggests, Capability(qstr) );
503       }
504     }
505
506     message << *argv << " [" << (ignorecase?'i':'_') << (names?'n':'_') << (requires?'r':'_') << (provides?'p':'_')
507     << (conflicts?'c':'_') << (obsoletes?'o':'_') << (recommends?'m':'_') << (supplements?'s':'_') << (enhacements?'e':'_')
508     << "] {" << endl;
509
510     Table t;
511     for_( it, q.begin(), q.end() )
512     {
513       if ( it->isKind( ResKind::srcpackage ) && !withSrcPackages )
514         continue;
515       t.row( it );
516     }
517     message << t << "}" << endl;
518   }
519
520   INT << "===[END]============================================" << endl << endl;
521   return 0;
522 }