1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/RepoManager.cc
20 #include "zypp/base/InputStream.h"
21 #include "zypp/base/Logger.h"
22 #include "zypp/base/Gettext.h"
23 #include "zypp/base/Function.h"
24 #include "zypp/base/Regex.h"
25 #include "zypp/PathInfo.h"
26 #include "zypp/TmpPath.h"
28 #include "zypp/repo/RepoException.h"
29 #include "zypp/RepoManager.h"
31 #include "zypp/media/MediaManager.h"
32 #include "zypp/MediaSetAccess.h"
33 #include "zypp/ExternalProgram.h"
34 #include "zypp/ManagedFile.h"
36 #include "zypp/parser/RepoFileReader.h"
37 #include "zypp/repo/yum/Downloader.h"
38 #include "zypp/parser/yum/RepoParser.h"
39 #include "zypp/repo/susetags/Downloader.h"
40 #include "zypp/parser/susetags/RepoParser.h"
41 #include "zypp/parser/plaindir/RepoParser.h"
43 #include "zypp/ZYppCallbacks.h"
46 #include "satsolver/pool.h"
47 #include "satsolver/repo.h"
48 #include "satsolver/repo_solv.h"
52 using namespace zypp::repo;
53 using namespace zypp::filesystem;
55 using namespace zypp::repo;
57 ///////////////////////////////////////////////////////////////////
59 { /////////////////////////////////////////////////////////////////
61 ///////////////////////////////////////////////////////////////////
63 // CLASS NAME : RepoManagerOptions
65 ///////////////////////////////////////////////////////////////////
67 RepoManagerOptions::RepoManagerOptions( const Pathname & root_r )
69 repoCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoCachePath() );
70 repoRawCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoMetadataPath() );
71 repoSolvCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoSolvfilesPath() );
72 repoPackagesCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoPackagesPath() );
73 knownReposPath = Pathname::assertprefix( root_r, ZConfig::instance().knownReposPath() );
74 probe = ZConfig::instance().repo_add_probe();
77 RepoManagerOptions RepoManagerOptions::makeTestSetup( const Pathname & root_r )
79 RepoManagerOptions ret;
80 ret.repoCachePath = root_r;
81 ret.repoRawCachePath = root_r/"raw";
82 ret.repoSolvCachePath = root_r/"solv";
83 ret.repoPackagesCachePath = root_r/"packages";
84 ret.knownReposPath = root_r/"repos.d";
88 ////////////////////////////////////////////////////////////////////////////
91 * \short Simple callback to collect the results
93 * Classes like RepoFileParser call the callback
94 * once per each repo in a file.
96 * Passing this functor as callback, you can collect
97 * all resuls at the end, without dealing with async
108 bool collect( const RepoInfo &repo )
110 repos.push_back(repo);
117 ////////////////////////////////////////////////////////////////////////////
120 * Reads RepoInfo's from a repo file.
122 * \param file pathname of the file to read.
124 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
126 MIL << "repo file: " << file << endl;
127 RepoCollector collector;
128 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
129 return collector.repos;
132 ////////////////////////////////////////////////////////////////////////////
134 std::list<RepoInfo> readRepoFile(const Url & repo_file)
136 // no interface to download a specific file, using workaround:
137 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
139 Pathname path(url.getPathName());
140 url.setPathName ("/");
141 MediaSetAccess access(url);
142 Pathname local = access.provideFile(path);
144 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
146 return repositories_in_file(local);
149 ////////////////////////////////////////////////////////////////////////////
152 * \short List of RepoInfo's from a directory
154 * Goes trough every file ending with ".repo" in a directory and adds all
155 * RepoInfo's contained in that file.
157 * \param dir pathname of the directory to read.
159 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
161 MIL << "directory " << dir << endl;
162 list<RepoInfo> repos;
163 list<Pathname> entries;
164 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
165 ZYPP_THROW(Exception("failed to read directory"));
167 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
168 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
170 if (str::regex_match(it->extension(), allowedRepoExt))
172 list<RepoInfo> tmp = repositories_in_file( *it );
173 repos.insert( repos.end(), tmp.begin(), tmp.end() );
175 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
176 //MIL << "ok" << endl;
182 ////////////////////////////////////////////////////////////////////////////
184 static void assert_alias( const RepoInfo &info )
186 if (info.alias().empty())
187 ZYPP_THROW(RepoNoAliasException());
190 ////////////////////////////////////////////////////////////////////////////
192 static void assert_urls( const RepoInfo &info )
194 if (info.baseUrlsEmpty())
195 ZYPP_THROW(RepoNoUrlException());
198 ////////////////////////////////////////////////////////////////////////////
201 * \short Calculates the raw cache path for a repository
203 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
206 return opt.repoRawCachePath / info.escaped_alias();
210 * \short Calculates the packages cache path for a repository
212 static Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
215 return opt.repoPackagesCachePath / info.escaped_alias();
218 static Pathname solv_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info)
221 return opt.repoSolvCachePath / info.escaped_alias();
224 ///////////////////////////////////////////////////////////////////
226 // CLASS NAME : RepoManager::Impl
228 ///////////////////////////////////////////////////////////////////
231 * \short RepoManager implementation.
233 struct RepoManager::Impl
235 Impl( const RepoManagerOptions &opt )
246 RepoManagerOptions options;
248 map<string, RepoInfo> _repoinfos;
251 /** Offer default Impl. */
252 static shared_ptr<Impl> nullimpl()
254 static shared_ptr<Impl> _nullimpl( new Impl );
259 friend Impl * rwcowClone<Impl>( const Impl * rhs );
260 /** clone for RWCOW_pointer */
262 { return new Impl( *this ); }
265 ///////////////////////////////////////////////////////////////////
267 /** \relates RepoManager::Impl Stream output */
268 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
270 return str << "RepoManager::Impl";
273 ///////////////////////////////////////////////////////////////////
275 // CLASS NAME : RepoManager
277 ///////////////////////////////////////////////////////////////////
279 RepoManager::RepoManager( const RepoManagerOptions &opt )
280 : _pimpl( new Impl(opt) )
283 ////////////////////////////////////////////////////////////////////////////
285 RepoManager::~RepoManager()
288 ////////////////////////////////////////////////////////////////////////////
290 std::list<RepoInfo> RepoManager::knownRepositories() const
294 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
296 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
297 for ( RepoInfoList::iterator it = repos.begin();
301 // set the metadata path for the repo
302 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
303 (*it).setMetadataPath(metadata_path);
305 // set the downloaded packages path for the repo
306 Pathname packages_path = packagescache_path_for_repoinfo(_pimpl->options, (*it));
307 (*it).setPackagesPath(packages_path);
312 return std::list<RepoInfo>();
317 ////////////////////////////////////////////////////////////////////////////
319 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
321 return rawcache_path_for_repoinfo(_pimpl->options, info );
324 ////////////////////////////////////////////////////////////////////////////
326 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
328 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
329 RepoType repokind = info.type();
332 switch ( repokind.toEnum() )
334 case RepoType::NONE_e:
335 // unknown, probe the local metadata
336 repokind = probe(rawpath.asUrl());
342 switch ( repokind.toEnum() )
344 case RepoType::RPMMD_e :
346 status = RepoStatus( rawpath + "/repodata/repomd.xml");
350 case RepoType::YAST2_e :
352 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
356 case RepoType::RPMPLAINDIR_e :
358 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
359 status = RepoStatus( rawpath + "/cookie");
363 case RepoType::NONE_e :
364 // Return default RepoStatus in case of RepoType::NONE
365 // indicating it should be created?
366 // ZYPP_THROW(RepoUnknownTypeException());
372 void RepoManager::touchIndexFile(const RepoInfo & info)
374 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
376 RepoType repokind = info.type();
377 if ( repokind.toEnum() == RepoType::NONE_e )
378 // unknown, probe the local metadata
379 repokind = probe(rawpath.asUrl());
380 // if still unknown, just return
381 if (repokind == RepoType::NONE_e)
385 switch ( repokind.toEnum() )
387 case RepoType::RPMMD_e :
388 p = Pathname(rawpath + "/repodata/repomd.xml");
391 case RepoType::YAST2_e :
392 p = Pathname(rawpath + "/content");
395 case RepoType::RPMPLAINDIR_e :
396 p = Pathname(rawpath + "/cookie");
399 case RepoType::NONE_e :
404 // touch the file, ignore error (they are logged anyway)
405 filesystem::touch(p);
408 RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata(
409 const RepoInfo &info,
411 RawMetadataRefreshPolicy policy )
415 RepoStatus oldstatus;
416 RepoStatus newstatus;
420 MIL << "Going to try to check whether refresh is needed for " << url << endl;
422 repo::RepoType repokind = info.type();
424 // if the type is unknown, try probing.
425 switch ( repokind.toEnum() )
427 case RepoType::NONE_e:
429 repokind = probe(url);
435 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
436 filesystem::assert_dir(rawpath);
437 oldstatus = metadataStatus(info);
439 // now we've got the old (cached) status, we can decide repo.refresh.delay
440 if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
442 // difference in seconds
443 double diff = difftime(
444 (Date::ValueType)Date::now(),
445 (Date::ValueType)oldstatus.timestamp()) / 60;
447 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
448 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
449 DBG << "last refresh = " << diff << " minutes ago" << endl;
451 if (diff < ZConfig::instance().repo_refresh_delay())
453 MIL << "Repository '" << info.alias()
454 << "' has been refreshed less than repo.refresh.delay ("
455 << ZConfig::instance().repo_refresh_delay()
456 << ") minutes ago. Advising to skip refresh" << endl;
457 return REPO_CHECK_DELAYED;
461 // create temp dir as sibling of rawpath
462 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
464 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
465 ( repokind.toEnum() == RepoType::YAST2_e ) )
467 MediaSetAccess media(url);
468 shared_ptr<repo::Downloader> downloader_ptr;
470 if ( repokind.toEnum() == RepoType::RPMMD_e )
471 downloader_ptr.reset(new yum::Downloader(info.path()));
473 downloader_ptr.reset( new susetags::Downloader(info.path()));
475 RepoStatus newstatus = downloader_ptr->status(media);
476 bool refresh = false;
477 if ( oldstatus.checksum() == newstatus.checksum() )
479 MIL << "repo has not changed" << endl;
480 if ( policy == RefreshForced )
482 MIL << "refresh set to forced" << endl;
488 MIL << "repo has changed, going to refresh" << endl;
493 touchIndexFile(info);
495 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
497 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
499 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
500 bool refresh = false;
501 if ( oldstatus.checksum() == newstatus.checksum() )
503 MIL << "repo has not changed" << endl;
504 if ( policy == RefreshForced )
506 MIL << "refresh set to forced" << endl;
512 MIL << "repo has changed, going to refresh" << endl;
517 touchIndexFile(info);
519 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
523 ZYPP_THROW(RepoUnknownTypeException(info));
526 catch ( const Exception &e )
529 ERR << "refresh check failed for " << url << endl;
533 return REFRESH_NEEDED; // default
536 void RepoManager::refreshMetadata( const RepoInfo &info,
537 RawMetadataRefreshPolicy policy,
538 const ProgressData::ReceiverFnc & progress )
543 // we will throw this later if no URL checks out fine
544 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
546 // try urls one by one
547 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
553 // check whether to refresh metadata
554 // if the check fails for this url, it throws, so another url will be checked
555 if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
558 MIL << "Going to refresh metadata from " << url << endl;
560 repo::RepoType repokind = info.type();
562 // if the type is unknown, try probing.
563 switch ( repokind.toEnum() )
565 case RepoType::NONE_e:
567 repokind = probe(*it);
569 if (repokind.toEnum() != RepoType::NONE_e)
571 // Adjust the probed type in RepoInfo
572 info.setProbedType( repokind ); // lazy init!
573 //save probed type only for repos in system
574 std::list<RepoInfo> repos = knownRepositories();
575 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
576 it != repos.end(); ++it )
578 if ( info.alias() == (*it).alias() )
580 RepoInfo modifiedrepo = info;
581 modifiedrepo.setType(repokind);
582 modifyRepository(info.alias(),modifiedrepo);
591 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
592 filesystem::assert_dir(rawpath);
594 // create temp dir as sibling of rawpath
595 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
597 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
598 ( repokind.toEnum() == RepoType::YAST2_e ) )
600 MediaSetAccess media(url);
601 shared_ptr<repo::Downloader> downloader_ptr;
603 if ( repokind.toEnum() == RepoType::RPMMD_e )
604 downloader_ptr.reset(new yum::Downloader(info.path()));
606 downloader_ptr.reset( new susetags::Downloader(info.path()));
609 * Given a downloader, sets the other repos raw metadata
610 * path as cache paths for the fetcher, so if another
611 * repo has the same file, it will not download it
612 * but copy it from the other repository
614 std::list<RepoInfo> repos = knownRepositories();
615 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
619 Pathname cachepath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
620 if ( PathInfo(cachepath).isExist() )
621 downloader_ptr->addCachePath(cachepath);
624 downloader_ptr->download( media, tmpdir.path());
626 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
628 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
630 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
632 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
635 file << newstatus.checksum() << endl;
641 ZYPP_THROW(RepoUnknownTypeException());
644 // ok we have the metadata, now exchange
647 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
648 filesystem::rename( rawpath, oldmetadata.path() );
649 // move the just downloaded there
650 filesystem::rename( tmpdir.path(), rawpath );
655 catch ( const Exception &e )
658 ERR << "Trying another url..." << endl;
660 // remember the exception caught for the *first URL*
661 // if all other URLs fail, the rexception will be thrown with the
662 // cause of the problem of the first URL remembered
663 if (it == info.baseUrlsBegin())
664 rexception.remember(e);
667 ERR << "No more urls..." << endl;
668 ZYPP_THROW(rexception);
671 ////////////////////////////////////////////////////////////////////////////
673 void RepoManager::cleanMetadata( const RepoInfo &info,
674 const ProgressData::ReceiverFnc & progressfnc )
676 ProgressData progress(100);
677 progress.sendTo(progressfnc);
679 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
683 void RepoManager::cleanPackages( const RepoInfo &info,
684 const ProgressData::ReceiverFnc & progressfnc )
686 ProgressData progress(100);
687 progress.sendTo(progressfnc);
689 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
693 void RepoManager::buildCache( const RepoInfo &info,
694 CacheBuildPolicy policy,
695 const ProgressData::ReceiverFnc & progressrcv )
698 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
700 filesystem::assert_dir(_pimpl->options.repoCachePath);
701 RepoStatus raw_metadata_status = metadataStatus(info);
702 if ( raw_metadata_status.empty() )
704 /* if there is no cache at this point, we refresh the raw
705 in case this is the first time - if it's !autorefresh,
706 we may still refresh */
707 refreshMetadata(info, RefreshIfNeeded, progressrcv );
708 raw_metadata_status = metadataStatus(info);
711 bool needs_cleaning = false;
712 if ( isCached( info ) )
714 MIL << info.alias() << " is already cached." << endl;
715 //data::RecordId id = store.lookupRepository(info.alias());
716 RepoStatus cache_status = cacheStatus(info);
718 if ( cache_status.checksum() == raw_metadata_status.checksum() )
720 MIL << info.alias() << " cache is up to date with metadata." << endl;
721 if ( policy == BuildIfNeeded ) {
725 MIL << info.alias() << " cache rebuild is forced" << endl;
729 needs_cleaning = true;
732 ProgressData progress(100);
733 callback::SendReport<ProgressReport> report;
734 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
735 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
743 MIL << info.alias() << " building cache..." << endl;
745 Pathname base = solv_path_for_repoinfo( _pimpl->options, info);
746 filesystem::assert_dir(base);
747 Pathname solvfile = base / "solv";
750 repo::RepoType repokind = info.type();
752 // if the type is unknown, try probing.
753 switch ( repokind.toEnum() )
755 case RepoType::NONE_e:
756 // unknown, probe the local metadata
757 repokind = probe(rawpath.asUrl());
763 MIL << "repo type is " << repokind << endl;
765 switch ( repokind.toEnum() )
767 case RepoType::RPMMD_e :
768 case RepoType::YAST2_e :
769 case RepoType::RPMPLAINDIR_e :
771 // Take care we unlink the solvfile on exception
772 ManagedFile guard( solvfile, filesystem::unlink );
775 const char *toFile = str::gsub(solvfile.asString(),"\"","\\\"").c_str();
776 if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
778 const char * from = str::gsub(
779 info.baseUrlsBegin()->getPathName(),"\"","\\\"").c_str();
780 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", from , toFile );
783 const char * from = str::gsub(rawpath.asString(),"\"","\\\"").c_str();
784 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", from, toFile );
786 MIL << "Executing: " << cmd.str() << endl;
787 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
790 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
791 WAR << " " << output;
792 cmd << " " << output;
795 int ret = prog.close();
798 RepoException ex(str::form("Failed to cache repo (%d).", ret));
799 ex.remember( cmd.str() );
804 guard.resetDispose();
808 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
812 switch ( repokind.toEnum() )
814 case RepoType::RPMMD_e :
817 CombinedProgressData subprogrcv( progress, 100);
818 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
819 parser.parse(rawpath);
823 case RepoType::YAST2_e :
826 CombinedProgressData subprogrcv( progress, 100);
827 parser::susetags::RepoParser parser(id, store, subprogrcv);
828 parser.parse(rawpath);
834 ZYPP_THROW(RepoUnknownTypeException());
837 // update timestamp and checksum
838 //store.updateRepositoryStatus(id, raw_metadata_status);
839 setCacheStatus(info, raw_metadata_status);
840 MIL << "Commit cache.." << endl;
845 ////////////////////////////////////////////////////////////////////////////
847 repo::RepoType RepoManager::probe( const Url &url ) const
849 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
851 // Handle non existing local directory in advance, as
852 // MediaSetAccess does not support it.
853 return repo::RepoType::NONE;
858 MediaSetAccess access(url);
859 if ( access.doesFileExist("/repodata/repomd.xml") )
860 return repo::RepoType::RPMMD;
861 if ( access.doesFileExist("/content") )
862 return repo::RepoType::YAST2;
864 // if it is a local url of type dir
865 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
867 Pathname path = Pathname(url.getPathName());
868 if ( PathInfo(path).isDir() )
870 // allow empty dirs for now
871 return repo::RepoType::RPMPLAINDIR;
875 catch ( const media::MediaException &e )
878 RepoException enew("Error trying to read from " + url.asString());
882 catch ( const Exception &e )
885 Exception enew("Unknown error reading from " + url.asString());
890 return repo::RepoType::NONE;
893 ////////////////////////////////////////////////////////////////////////////
895 void RepoManager::cleanCache( const RepoInfo &info,
896 const ProgressData::ReceiverFnc & progressrcv )
898 ProgressData progress(100);
899 progress.sendTo(progressrcv);
902 filesystem::recursive_rmdir(solv_path_for_repoinfo(_pimpl->options, info));
907 ////////////////////////////////////////////////////////////////////////////
909 bool RepoManager::isCached( const RepoInfo &info ) const
911 return PathInfo(solv_path_for_repoinfo( _pimpl->options, info ) / "solv").isExist();
914 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
917 Pathname cookiefile = solv_path_for_repoinfo(_pimpl->options, info) / "cookie";
919 return RepoStatus::fromCookieFile(cookiefile);
922 void RepoManager::setCacheStatus( const RepoInfo &info, const RepoStatus &status )
924 Pathname base = solv_path_for_repoinfo(_pimpl->options, info);
925 filesystem::assert_dir(base);
926 Pathname cookiefile = base / "cookie";
928 status.saveToCookieFile(cookiefile);
931 void RepoManager::loadFromCache( const RepoInfo & info,
932 const ProgressData::ReceiverFnc & progressrcv )
935 Pathname solvfile = solv_path_for_repoinfo(_pimpl->options, info) / "solv";
937 if ( ! PathInfo(solvfile).isExist() )
938 ZYPP_THROW(RepoNotCachedException(info));
942 sat::Pool::instance().addRepoSolv( solvfile, info );
944 catch ( const Exception & exp )
947 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
948 cleanCache( info, progressrcv );
949 buildCache( info, BuildIfNeeded, progressrcv );
951 sat::Pool::instance().addRepoSolv( solvfile, info );
955 ////////////////////////////////////////////////////////////////////////////
958 * Generate a non existing filename in a directory, using a base
959 * name. For example if a directory contains 3 files
965 * If you try to generate a unique filename for this directory,
966 * based on "ruu" you will get "ruu", but if you use the base
967 * "foo" you will get "foo_1"
969 * \param dir Directory where the file needs to be unique
970 * \param basefilename string to base the filename on.
972 static Pathname generate_non_existing_name( const Pathname &dir,
973 const std::string &basefilename )
975 string final_filename = basefilename;
977 while ( PathInfo(dir + final_filename).isExist() )
979 final_filename = basefilename + "_" + str::numstring(counter);
982 return dir + Pathname(final_filename);
985 ////////////////////////////////////////////////////////////////////////////
988 * \short Generate a related filename from a repo info
990 * From a repo info, it will try to use the alias as a filename
991 * escaping it if necessary. Other fallbacks can be added to
992 * this function in case there is no way to use the alias
994 static std::string generate_filename( const RepoInfo &info )
998 std::string filename = info.alias();
999 // replace slashes with underscores
1000 size_t pos = filename.find(fnd);
1001 while(pos!=string::npos)
1003 filename.replace(pos,fnd.length(),rep);
1004 pos = filename.find(fnd,pos+rep.length());
1006 filename = Pathname(filename).extend(".repo").asString();
1007 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
1012 ////////////////////////////////////////////////////////////////////////////
1014 void RepoManager::addRepository( const RepoInfo &info,
1015 const ProgressData::ReceiverFnc & progressrcv )
1019 ProgressData progress(100);
1020 callback::SendReport<ProgressReport> report;
1021 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1022 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1025 std::list<RepoInfo> repos = knownRepositories();
1026 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1030 if ( info.alias() == (*it).alias() )
1031 ZYPP_THROW(RepoAlreadyExistsException(info));
1034 RepoInfo tosave = info;
1036 // check the first url for now
1037 if ( _pimpl->options.probe )
1039 DBG << "unknown repository type, probing" << endl;
1041 RepoType probedtype;
1042 probedtype = probe(*tosave.baseUrlsBegin());
1043 if ( tosave.baseUrlsSize() > 0 )
1045 if ( probedtype == RepoType::NONE )
1046 ZYPP_THROW(RepoUnknownTypeException());
1048 tosave.setType(probedtype);
1054 // assert the directory exists
1055 filesystem::assert_dir(_pimpl->options.knownReposPath);
1057 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1058 generate_filename(tosave));
1059 // now we have a filename that does not exists
1060 MIL << "Saving repo in " << repofile << endl;
1062 std::ofstream file(repofile.c_str());
1064 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1067 tosave.dumpRepoOn(file);
1069 MIL << "done" << endl;
1072 void RepoManager::addRepositories( const Url &url,
1073 const ProgressData::ReceiverFnc & progressrcv )
1075 std::list<RepoInfo> knownrepos = knownRepositories();
1076 std::list<RepoInfo> repos = readRepoFile(url);
1077 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1081 // look if the alias is in the known repos.
1082 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1083 kit != knownrepos.end();
1086 if ( (*it).alias() == (*kit).alias() )
1088 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1089 ZYPP_THROW(RepoAlreadyExistsException(*it));
1094 string filename = Pathname(url.getPathName()).basename();
1096 if ( filename == Pathname() )
1097 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1099 // assert the directory exists
1100 filesystem::assert_dir(_pimpl->options.knownReposPath);
1102 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1103 // now we have a filename that does not exists
1104 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1106 std::ofstream file(repofile.c_str());
1108 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1111 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1115 MIL << "Saving " << (*it).alias() << endl;
1116 (*it).dumpRepoOn(file);
1118 MIL << "done" << endl;
1121 ////////////////////////////////////////////////////////////////////////////
1123 void RepoManager::removeRepository( const RepoInfo & info,
1124 const ProgressData::ReceiverFnc & progressrcv)
1126 ProgressData progress;
1127 callback::SendReport<ProgressReport> report;
1128 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1129 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1131 MIL << "Going to delete repo " << info.alias() << endl;
1133 std::list<RepoInfo> repos = knownRepositories();
1134 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1138 // they can be the same only if the provided is empty, that means
1139 // the provided repo has no alias
1141 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1144 // TODO match by url
1146 // we have a matcing repository, now we need to know
1147 // where it does come from.
1148 RepoInfo todelete = *it;
1149 if (todelete.filepath().empty())
1151 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1155 // figure how many repos are there in the file:
1156 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1157 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1159 // easy, only this one, just delete the file
1160 if ( filesystem::unlink(todelete.filepath()) != 0 )
1162 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1164 MIL << todelete.alias() << " sucessfully deleted." << endl;
1168 // there are more repos in the same file
1169 // write them back except the deleted one.
1171 //std::ofstream file(tmp.path().c_str());
1173 // assert the directory exists
1174 filesystem::assert_dir(todelete.filepath().dirname());
1176 std::ofstream file(todelete.filepath().c_str());
1178 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1179 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1181 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1182 fit != filerepos.end();
1185 if ( (*fit).alias() != todelete.alias() )
1186 (*fit).dumpRepoOn(file);
1190 CombinedProgressData subprogrcv(progress, 70);
1191 CombinedProgressData cleansubprogrcv(progress, 30);
1192 // now delete it from cache
1193 if ( isCached(todelete) )
1194 cleanCache( todelete, subprogrcv);
1195 // now delete metadata (#301037)
1196 cleanMetadata( todelete, cleansubprogrcv);
1197 MIL << todelete.alias() << " sucessfully deleted." << endl;
1199 } // else filepath is empty
1202 // should not be reached on a sucess workflow
1203 ZYPP_THROW(RepoNotFoundException(info));
1206 ////////////////////////////////////////////////////////////////////////////
1208 void RepoManager::modifyRepository( const std::string &alias,
1209 const RepoInfo & newinfo,
1210 const ProgressData::ReceiverFnc & progressrcv )
1212 RepoInfo toedit = getRepositoryInfo(alias);
1214 // check if the new alias already exists when renaming the repo
1215 if (alias != newinfo.alias())
1217 std::list<RepoInfo> repos = knownRepositories();
1218 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1222 if ( newinfo.alias() == (*it).alias() )
1223 ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1227 if (toedit.filepath().empty())
1229 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1233 // figure how many repos are there in the file:
1234 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1236 // there are more repos in the same file
1237 // write them back except the deleted one.
1239 //std::ofstream file(tmp.path().c_str());
1241 // assert the directory exists
1242 filesystem::assert_dir(toedit.filepath().dirname());
1244 std::ofstream file(toedit.filepath().c_str());
1246 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1247 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1249 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1250 fit != filerepos.end();
1253 // if the alias is different, dump the original
1254 // if it is the same, dump the provided one
1255 if ( (*fit).alias() != toedit.alias() )
1256 (*fit).dumpRepoOn(file);
1258 newinfo.dumpRepoOn(file);
1263 ////////////////////////////////////////////////////////////////////////////
1265 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1266 const ProgressData::ReceiverFnc & progressrcv )
1268 std::list<RepoInfo> repos = knownRepositories();
1269 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1273 if ( (*it).alias() == alias )
1277 info.setAlias(info.alias());
1278 ZYPP_THROW(RepoNotFoundException(info));
1281 ////////////////////////////////////////////////////////////////////////////
1283 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1284 const url::ViewOption & urlview,
1285 const ProgressData::ReceiverFnc & progressrcv )
1287 std::list<RepoInfo> repos = knownRepositories();
1288 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1292 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1293 urlit != (*it).baseUrlsEnd();
1296 if ((*urlit).asString(urlview) == url.asString(urlview))
1301 info.setAlias(info.alias());
1302 info.setBaseUrl(url);
1303 ZYPP_THROW(RepoNotFoundException(info));
1306 ////////////////////////////////////////////////////////////////////////////
1308 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1310 return str << *obj._pimpl;
1313 /////////////////////////////////////////////////////////////////
1315 ///////////////////////////////////////////////////////////////////