1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/RepoManager.cc
19 #include "zypp/base/InputStream.h"
20 #include "zypp/base/Logger.h"
21 #include "zypp/base/Gettext.h"
22 #include "zypp/base/Function.h"
23 #include "zypp/base/Regex.h"
24 #include "zypp/PathInfo.h"
25 #include "zypp/TmpPath.h"
27 #include "zypp/repo/RepoException.h"
28 #include "zypp/RepoManager.h"
30 #include "zypp/cache/SolvStore.h"
31 //#include "zypp/repo/cached/RepoImpl.h"
32 #include "zypp/media/MediaManager.h"
33 #include "zypp/MediaSetAccess.h"
34 #include "zypp/ExternalProgram.h"
36 #include "zypp/parser/RepoFileReader.h"
37 #include "zypp/repo/yum/Downloader.h"
38 #include "zypp/parser/yum/RepoParser.h"
39 //#include "zypp/parser/plaindir/RepoParser.h"
40 #include "zypp/repo/susetags/Downloader.h"
41 #include "zypp/parser/susetags/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()
69 repoCachePath = ZConfig::instance().repoCachePath();
70 repoRawCachePath = ZConfig::instance().repoMetadataPath();
71 knownReposPath = ZConfig::instance().knownReposPath();
74 ////////////////////////////////////////////////////////////////////////////
77 * \short Simple callback to collect the results
79 * Classes like RepoFileParser call the callback
80 * once per each repo in a file.
82 * Passing this functor as callback, you can collect
83 * all resuls at the end, without dealing with async
98 bool collect( const RepoInfo &repo )
100 //MIL << "here in collector: " << repo.alias() << endl;
101 repos.push_back(repo);
102 //MIL << "added: " << repo.alias() << endl;
109 ////////////////////////////////////////////////////////////////////////////
112 * \short Internal version of clean cache
114 * Takes an extra SolvStore reference, so we avoid internally
115 * having 2 SolvStores writing to the same database.
117 static void cleanCacheInternal( cache::SolvStore &store,
118 const RepoInfo &info,
119 const ProgressData::ReceiverFnc & progressrcv = ProgressData::ReceiverFnc() )
121 ProgressData progress;
122 callback::SendReport<ProgressReport> report;
123 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
124 progress.name(str::form(_("Cleaning repository '%s' cache"), info.name().c_str()));
126 if ( !store.isCached(info.alias()) )
129 MIL << info.alias() << " cleaning cache..." << endl;
130 data::RecordId id = store.lookupRepository(info.alias());
132 CombinedProgressData subprogrcv(progress);
134 store.cleanRepository(id, subprogrcv);
137 ////////////////////////////////////////////////////////////////////////////
140 * Reads RepoInfo's from a repo file.
142 * \param file pathname of the file to read.
144 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
146 MIL << "repo file: " << file << endl;
147 RepoCollector collector;
148 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
149 return collector.repos;
152 ////////////////////////////////////////////////////////////////////////////
154 std::list<RepoInfo> readRepoFile(const Url & repo_file)
156 // no interface to download a specific file, using workaround:
157 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
159 Pathname path(url.getPathName());
160 url.setPathName ("/");
161 MediaSetAccess access(url);
162 Pathname local = access.provideFile(path);
164 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
166 return repositories_in_file(local);
169 ////////////////////////////////////////////////////////////////////////////
172 * \short List of RepoInfo's from a directory
174 * Goes trough every file ending with ".repo" in a directory and adds all
175 * RepoInfo's contained in that file.
177 * \param dir pathname of the directory to read.
179 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
181 MIL << "directory " << dir << endl;
182 list<RepoInfo> repos;
183 list<Pathname> entries;
184 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
185 ZYPP_THROW(Exception("failed to read directory"));
187 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
188 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
190 if (str::regex_match(it->extension(), allowedRepoExt))
192 list<RepoInfo> tmp = repositories_in_file( *it );
193 repos.insert( repos.end(), tmp.begin(), tmp.end() );
195 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
196 //MIL << "ok" << endl;
202 ////////////////////////////////////////////////////////////////////////////
204 static void assert_alias( const RepoInfo &info )
206 if (info.alias().empty())
207 ZYPP_THROW(RepoNoAliasException());
210 ////////////////////////////////////////////////////////////////////////////
212 static void assert_urls( const RepoInfo &info )
214 if (info.baseUrlsEmpty())
215 ZYPP_THROW(RepoNoUrlException());
218 ////////////////////////////////////////////////////////////////////////////
221 * \short Calculates the raw cache path for a repository
223 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
226 return opt.repoRawCachePath + info.alias();
229 ///////////////////////////////////////////////////////////////////
231 // CLASS NAME : RepoManager::Impl
233 ///////////////////////////////////////////////////////////////////
236 * \short RepoManager implementation.
238 struct RepoManager::Impl
240 Impl( const RepoManagerOptions &opt )
251 RepoManagerOptions options;
254 /** Offer default Impl. */
255 static shared_ptr<Impl> nullimpl()
257 static shared_ptr<Impl> _nullimpl( new Impl );
262 friend Impl * rwcowClone<Impl>( const Impl * rhs );
263 /** clone for RWCOW_pointer */
265 { return new Impl( *this ); }
268 ///////////////////////////////////////////////////////////////////
270 /** \relates RepoManager::Impl Stream output */
271 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
273 return str << "RepoManager::Impl";
276 ///////////////////////////////////////////////////////////////////
278 // CLASS NAME : RepoManager
280 ///////////////////////////////////////////////////////////////////
282 RepoManager::RepoManager( const RepoManagerOptions &opt )
283 : _pimpl( new Impl(opt) )
286 ////////////////////////////////////////////////////////////////////////////
288 RepoManager::~RepoManager()
291 ////////////////////////////////////////////////////////////////////////////
293 std::list<RepoInfo> RepoManager::knownRepositories() const
297 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
299 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
300 for ( RepoInfoList::iterator it = repos.begin();
304 // set the metadata path for the repo
305 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
306 (*it).setMetadataPath(metadata_path);
311 return std::list<RepoInfo>();
316 ////////////////////////////////////////////////////////////////////////////
318 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
320 return rawcache_path_for_repoinfo(_pimpl->options, info );
323 ////////////////////////////////////////////////////////////////////////////
325 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
327 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
328 RepoType repokind = info.type();
331 switch ( repokind.toEnum() )
333 case RepoType::NONE_e:
334 // unknown, probe the local metadata
335 repokind = probe(rawpath.asUrl());
341 switch ( repokind.toEnum() )
343 case RepoType::RPMMD_e :
345 status = RepoStatus( rawpath + "/repodata/repomd.xml");
349 case RepoType::YAST2_e :
351 // the order of RepoStatus && RepoStatus matters! (#304310)
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 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
410 RawMetadataRefreshPolicy policy )
414 RepoStatus oldstatus;
415 RepoStatus newstatus;
419 MIL << "Going to try to check whether refresh is needed for " << url << endl;
421 repo::RepoType repokind = info.type();
423 // if the type is unknown, try probing.
424 switch ( repokind.toEnum() )
426 case RepoType::NONE_e:
428 repokind = probe(url);
434 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
435 filesystem::assert_dir(rawpath);
436 oldstatus = metadataStatus(info);
438 // now we've got the old (cached) status, we can decide repo.refresh.delay
439 if (policy != RefreshForced)
441 // difference in seconds
442 double diff = difftime(
443 (Date::ValueType)Date::now(),
444 (Date::ValueType)oldstatus.timestamp()) / 60;
446 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
447 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
448 DBG << "last refresh = " << diff << " minutes ago" << endl;
450 if (diff < ZConfig::instance().repo_refresh_delay())
452 MIL << "Repository '" << info.alias()
453 << "' has been refreshed less than repo.refresh.delay ("
454 << ZConfig::instance().repo_refresh_delay()
455 << ") minutes ago. Advising to skip refresh" << endl;
460 // create temp dir as sibling of rawpath
461 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
463 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
464 ( repokind.toEnum() == RepoType::YAST2_e ) )
466 MediaSetAccess media(url);
467 shared_ptr<repo::Downloader> downloader_ptr;
469 if ( repokind.toEnum() == RepoType::RPMMD_e )
470 downloader_ptr.reset(new yum::Downloader(info.path()));
472 downloader_ptr.reset( new susetags::Downloader(info.path()));
474 RepoStatus newstatus = downloader_ptr->status(media);
475 bool refresh = false;
476 if ( oldstatus.checksum() == newstatus.checksum() )
478 MIL << "repo has not changed" << endl;
479 if ( policy == RefreshForced )
481 MIL << "refresh set to forced" << endl;
487 MIL << "repo has changed, going to refresh" << endl;
492 touchIndexFile(info);
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);
524 ZYPP_THROW(RepoUnknownTypeException());
527 catch ( const Exception &e )
530 ERR << "refresh check failed for " << url << endl;
534 return true; // default
537 void RepoManager::refreshMetadata( const RepoInfo &info,
538 RawMetadataRefreshPolicy policy,
539 const ProgressData::ReceiverFnc & progress )
544 // we will throw this later if no URL checks out fine
545 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
547 // try urls one by one
548 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
554 // check whether to refresh metadata
555 // if the check fails for this url, it throws, so another url will be checked
556 if (!checkIfToRefreshMetadata(info, url, policy))
559 MIL << "Going to refresh metadata from " << url << endl;
561 repo::RepoType repokind = info.type();
563 // if the type is unknown, try probing.
564 switch ( repokind.toEnum() )
566 case RepoType::NONE_e:
568 repokind = probe(*it);
574 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
575 filesystem::assert_dir(rawpath);
577 // create temp dir as sibling of rawpath
578 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
580 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
581 ( repokind.toEnum() == RepoType::YAST2_e ) )
583 MediaSetAccess media(url);
584 shared_ptr<repo::Downloader> downloader_ptr;
586 if ( repokind.toEnum() == RepoType::RPMMD_e )
587 downloader_ptr.reset(new yum::Downloader(info.path()));
589 downloader_ptr.reset( new susetags::Downloader(info.path()));
592 * Given a downloader, sets the other repos raw metadata
593 * path as cache paths for the fetcher, so if another
594 * repo has the same file, it will not download it
595 * but copy it from the other repository
597 std::list<RepoInfo> repos = knownRepositories();
598 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
602 downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
605 downloader_ptr->download( media, tmpdir.path());
608 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
610 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
612 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
614 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
617 file << newstatus.checksum() << endl;
624 ZYPP_THROW(RepoUnknownTypeException());
627 // ok we have the metadata, now exchange
629 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
630 filesystem::rename( rawpath, oldmetadata.path() );
631 // move the just downloaded there
632 filesystem::rename( tmpdir.path(), rawpath );
636 catch ( const Exception &e )
639 ERR << "Trying another url..." << endl;
641 // remember the exception caught for the *first URL*
642 // if all other URLs fail, the rexception will be thrown with the
643 // cause of the problem of the first URL remembered
644 if (it == info.baseUrlsBegin())
645 rexception.remember(e);
648 ERR << "No more urls..." << endl;
649 ZYPP_THROW(rexception);
652 ////////////////////////////////////////////////////////////////////////////
654 void RepoManager::cleanMetadata( const RepoInfo &info,
655 const ProgressData::ReceiverFnc & progressfnc )
657 ProgressData progress(100);
658 progress.sendTo(progressfnc);
660 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
664 void RepoManager::buildCache( const RepoInfo &info,
665 CacheBuildPolicy policy,
666 const ProgressData::ReceiverFnc & progressrcv )
669 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
671 Pathname base = _pimpl->options.repoCachePath + info.alias();
672 Pathname solvfile = base.extend(".solv");
674 //cache::SolvStore store(_pimpl->options.repoCachePath);
676 RepoStatus raw_metadata_status = metadataStatus(info);
677 if ( raw_metadata_status.empty() )
679 ZYPP_THROW(RepoMetadataException(info));
682 bool needs_cleaning = false;
683 if ( isCached( info ) )
685 MIL << info.alias() << " is already cached." << endl;
686 //data::RecordId id = store.lookupRepository(info.alias());
687 RepoStatus cache_status = cacheStatus(info);
689 if ( cache_status.checksum() == raw_metadata_status.checksum() )
691 MIL << info.alias() << " cache is up to date with metadata." << endl;
692 if ( policy == BuildIfNeeded ) {
696 MIL << info.alias() << " cache rebuild is forced" << endl;
700 needs_cleaning = true;
703 ProgressData progress(100);
704 callback::SendReport<ProgressReport> report;
705 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
706 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
711 // Pathname name = _pimpl->options.repoCachePath;
712 // //data::RecordId id = store.lookupRepository(info.alias());
715 // name += os.str() + ".solv";
717 // cleanCacheInternal( store, info);
721 MIL << info.alias() << " building cache..." << endl;
722 //data::RecordId id = store.lookupOrAppendRepository(info.alias());
724 repo::RepoType repokind = info.type();
726 // if the type is unknown, try probing.
727 switch ( repokind.toEnum() )
729 case RepoType::NONE_e:
730 // unknown, probe the local metadata
731 repokind = probe(rawpath.asUrl());
737 <<<<<<< HEAD:zypp/RepoManager.cc
740 MIL << "repo type is " << repokind << endl;
742 >>>>>>> by now the repomanager returns an invalid repo
743 but loads the solv file in the global pool
744 (should this be automatic?):zypp/RepoManager.cc
745 switch ( repokind.toEnum() )
747 case RepoType::RPMMD_e :
748 case RepoType::YAST2_e :
750 // string cmd = "repo2solv.sh \"";
751 // cmd += rawpath.asString() + "\" > " + solvfile.asString();
752 // int ret = system (cmd.c_str());
753 // if (WIFEXITED (ret) && WEXITSTATUS (ret) != 0)
754 // ZYPP_THROW(RepoUnknownTypeException());
755 MIL << "Executing solv converter" << endl;
756 string cmd( str::form( "/usr/bin/repo2solv.sh \"%s\" > %s", rawpath.asString().c_str(), solvfile.asString().c_str() ) );
757 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
758 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
759 MIL << " " << output;
761 int ret = prog.close();
765 ZYPP_THROW(Exception("Unhandled repostory type"));
769 switch ( repokind.toEnum() )
771 case RepoType::RPMMD_e :
774 CombinedProgressData subprogrcv( progress, 100);
775 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
776 parser.parse(rawpath);
780 case RepoType::YAST2_e :
783 CombinedProgressData subprogrcv( progress, 100);
784 parser::susetags::RepoParser parser(id, store, subprogrcv);
785 parser.parse(rawpath);
791 case RepoType::RPMPLAINDIR_e :
793 CombinedProgressData subprogrcv( progress, 100);
794 InputStream is(rawpath + "cookie");
796 getline( is.stream(), buffer);
798 parser::plaindir::RepoParser parser(id, store, subprogrcv);
799 parser.parse(url.getPathName());
804 ZYPP_THROW(RepoUnknownTypeException());
807 // update timestamp and checksum
808 //store.updateRepositoryStatus(id, raw_metadata_status);
809 setCacheStatus(info.alias(), raw_metadata_status);
810 MIL << "Commit cache.." << endl;
815 ////////////////////////////////////////////////////////////////////////////
817 repo::RepoType RepoManager::probe( const Url &url ) const
819 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
821 // Handle non existing local directory in advance, as
822 // MediaSetAccess does not support it.
823 return repo::RepoType::NONE;
828 MediaSetAccess access(url);
829 if ( access.doesFileExist("/repodata/repomd.xml") )
830 return repo::RepoType::RPMMD;
831 if ( access.doesFileExist("/content") )
832 return repo::RepoType::YAST2;
834 // if it is a local url of type dir
835 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
837 Pathname path = Pathname(url.getPathName());
838 if ( PathInfo(path).isDir() )
840 // allow empty dirs for now
841 return repo::RepoType::RPMPLAINDIR;
845 catch ( const media::MediaException &e )
848 RepoException enew("Error trying to read from " + url.asString());
852 catch ( const Exception &e )
855 Exception enew("Unknown error reading from " + url.asString());
860 return repo::RepoType::NONE;
863 ////////////////////////////////////////////////////////////////////////////
865 void RepoManager::cleanCache( const RepoInfo &info,
866 const ProgressData::ReceiverFnc & progressrcv )
868 Pathname name = _pimpl->options.repoCachePath;
869 name += info.alias() + ".solv";
873 ////////////////////////////////////////////////////////////////////////////
875 bool RepoManager::isCached( const RepoInfo &info ) const
877 Pathname name = _pimpl->options.repoCachePath;
878 return PathInfo(name + Pathname(info.alias()).extend(".solv")).isExist();
881 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
884 Pathname base = _pimpl->options.repoCachePath + info.alias();
885 Pathname solvfile = base.extend(".solv");
886 Pathname cookiefile = base.extend(".cookie");
888 std::ifstream file(cookiefile.c_str());
890 ZYPP_THROW (Exception( "Can't open " + cookiefile.asString() ) );
894 while(file && !file.eof()) {
895 getline(file, buffer);
898 std::vector<std::string> words;
899 if ( str::split( buffer, std::back_inserter(words) ) != 2 )
900 ZYPP_THROW (Exception( "corrupt file " + cookiefile.asString() ) );
902 status.setTimestamp(Date(str::strtonum<time_t>(words[1])));
903 status.setChecksum(words[0]);
907 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
909 Pathname base = _pimpl->options.repoCachePath + alias;
910 Pathname cookiefile = base.extend(".cookie");
912 std::ofstream file(cookiefile.c_str());
914 ZYPP_THROW (Exception( "Can't open " + cookiefile.asString() ) );
920 map<data::RecordId, Repo *> repo2solv;
922 Repository RepoManager::createFromCache( const RepoInfo &info,
923 const ProgressData::ReceiverFnc & progressrcv )
925 callback::SendReport<ProgressReport> report;
926 ProgressData progress;
927 progress.sendTo(ProgressReportAdaptor( progressrcv, report ));
928 //progress.sendTo( progressrcv );
929 progress.name(str::form(_("Reading repository '%s' cache"), info.name().c_str()));
931 //_pimpl->options.repoCachePath
932 if ( ! isCached( info ) )
933 ZYPP_THROW(RepoNotCachedException());
935 MIL << "Repository " << info.alias() << " is cached" << endl;
937 sat::Pool satpool( sat::Pool::instance() );
939 <<<<<<< HEAD:zypp/RepoManager.cc
940 //Pathname name = _pimpl->options.repoCachePath + Pathname(info.alias()).extend(".solv");
943 Pathname solvfile = (_pimpl->options.repoCachePath + info.alias()).extend(".solv");
945 >>>>>>> by now the repomanager returns an invalid repo
946 but loads the solv file in the global pool
947 (should this be automatic?):zypp/RepoManager.cc
950 satpool.addRepoSolv(solvfile, info.alias());
952 catch ( const Exception &e )
954 <<<<<<< HEAD:zypp/RepoManager.cc
958 >>>>>>> by now the repomanager returns an invalid repo
959 but loads the solv file in the global pool
960 (should this be automatic?):zypp/RepoManager.cc
963 CombinedProgressData subprogrcv(progress);
965 // repo::cached::RepoOptions opts( info, _pimpl->options.repoCachePath, id );
966 // opts.readingResolvablesProgress = subprogrcv;
967 // //opts.repo = repo;
968 // repo::cached::RepoImpl::Ptr repoimpl =
969 // new repo::cached::RepoImpl( opts );
971 // repoimpl->resolvables();
972 // read the resolvables from cache
973 return Repository::noRepository;
976 ////////////////////////////////////////////////////////////////////////////
979 * Generate a non existing filename in a directory, using a base
980 * name. For example if a directory contains 3 files
986 * If you try to generate a unique filename for this directory,
987 * based on "ruu" you will get "ruu", but if you use the base
988 * "foo" you will get "foo_1"
990 * \param dir Directory where the file needs to be unique
991 * \param basefilename string to base the filename on.
993 static Pathname generate_non_existing_name( const Pathname &dir,
994 const std::string &basefilename )
996 string final_filename = basefilename;
998 while ( PathInfo(dir + final_filename).isExist() )
1000 final_filename = basefilename + "_" + str::numstring(counter);
1003 return dir + Pathname(final_filename);
1006 ////////////////////////////////////////////////////////////////////////////
1009 * \short Generate a related filename from a repo info
1011 * From a repo info, it will try to use the alias as a filename
1012 * escaping it if necessary. Other fallbacks can be added to
1013 * this function in case there is no way to use the alias
1015 static std::string generate_filename( const RepoInfo &info )
1017 std::string fnd="/";
1018 std::string rep="_";
1019 std::string filename = info.alias();
1020 // replace slashes with underscores
1021 size_t pos = filename.find(fnd);
1022 while(pos!=string::npos)
1024 filename.replace(pos,fnd.length(),rep);
1025 pos = filename.find(fnd,pos+rep.length());
1027 filename = Pathname(filename).extend(".repo").asString();
1028 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
1033 ////////////////////////////////////////////////////////////////////////////
1035 void RepoManager::addRepository( const RepoInfo &info,
1036 const ProgressData::ReceiverFnc & progressrcv )
1040 ProgressData progress(100);
1041 callback::SendReport<ProgressReport> report;
1042 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1043 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1046 std::list<RepoInfo> repos = knownRepositories();
1047 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1051 if ( info.alias() == (*it).alias() )
1052 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
1055 RepoInfo tosave = info;
1057 // check the first url for now
1058 if ( ZConfig::instance().repo_add_probe()
1059 || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
1061 DBG << "unknown repository type, probing" << endl;
1063 RepoType probedtype;
1064 probedtype = probe(*tosave.baseUrlsBegin());
1065 if ( tosave.baseUrlsSize() > 0 )
1067 if ( probedtype == RepoType::NONE )
1068 ZYPP_THROW(RepoUnknownTypeException());
1070 tosave.setType(probedtype);
1076 // assert the directory exists
1077 filesystem::assert_dir(_pimpl->options.knownReposPath);
1079 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1080 generate_filename(tosave));
1081 // now we have a filename that does not exists
1082 MIL << "Saving repo in " << repofile << endl;
1084 std::ofstream file(repofile.c_str());
1086 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1089 tosave.dumpRepoOn(file);
1091 MIL << "done" << endl;
1094 void RepoManager::addRepositories( const Url &url,
1095 const ProgressData::ReceiverFnc & progressrcv )
1097 std::list<RepoInfo> knownrepos = knownRepositories();
1098 std::list<RepoInfo> repos = readRepoFile(url);
1099 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1103 // look if the alias is in the known repos.
1104 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1105 kit != knownrepos.end();
1108 if ( (*it).alias() == (*kit).alias() )
1110 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1111 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1116 string filename = Pathname(url.getPathName()).basename();
1118 if ( filename == Pathname() )
1119 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1121 // assert the directory exists
1122 filesystem::assert_dir(_pimpl->options.knownReposPath);
1124 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1125 // now we have a filename that does not exists
1126 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1128 std::ofstream file(repofile.c_str());
1130 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1133 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1137 MIL << "Saving " << (*it).alias() << endl;
1138 (*it).dumpRepoOn(file);
1140 MIL << "done" << endl;
1143 ////////////////////////////////////////////////////////////////////////////
1145 void RepoManager::removeRepository( const RepoInfo & info,
1146 const ProgressData::ReceiverFnc & progressrcv)
1148 ProgressData progress;
1149 callback::SendReport<ProgressReport> report;
1150 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1151 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1153 MIL << "Going to delete repo " << info.alias() << endl;
1155 std::list<RepoInfo> repos = knownRepositories();
1156 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1160 // they can be the same only if the provided is empty, that means
1161 // the provided repo has no alias
1163 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1166 // TODO match by url
1168 // we have a matcing repository, now we need to know
1169 // where it does come from.
1170 RepoInfo todelete = *it;
1171 if (todelete.filepath().empty())
1173 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1177 // figure how many repos are there in the file:
1178 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1179 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1181 // easy, only this one, just delete the file
1182 if ( filesystem::unlink(todelete.filepath()) != 0 )
1184 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1186 MIL << todelete.alias() << " sucessfully deleted." << endl;
1190 // there are more repos in the same file
1191 // write them back except the deleted one.
1193 //std::ofstream file(tmp.path().c_str());
1195 // assert the directory exists
1196 filesystem::assert_dir(todelete.filepath().dirname());
1198 std::ofstream file(todelete.filepath().c_str());
1200 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1201 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1203 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1204 fit != filerepos.end();
1207 if ( (*fit).alias() != todelete.alias() )
1208 (*fit).dumpRepoOn(file);
1212 CombinedProgressData subprogrcv(progress, 70);
1213 CombinedProgressData cleansubprogrcv(progress, 30);
1214 // now delete it from cache
1215 if ( isCached(todelete) )
1216 cleanCache( todelete, subprogrcv);
1217 // now delete metadata (#301037)
1218 cleanMetadata( todelete, cleansubprogrcv);
1219 MIL << todelete.alias() << " sucessfully deleted." << endl;
1221 } // else filepath is empty
1224 // should not be reached on a sucess workflow
1225 ZYPP_THROW(RepoNotFoundException(info));
1228 ////////////////////////////////////////////////////////////////////////////
1230 void RepoManager::modifyRepository( const std::string &alias,
1231 const RepoInfo & newinfo,
1232 const ProgressData::ReceiverFnc & progressrcv )
1234 RepoInfo toedit = getRepositoryInfo(alias);
1236 if (toedit.filepath().empty())
1238 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1242 // figure how many repos are there in the file:
1243 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1245 // there are more repos in the same file
1246 // write them back except the deleted one.
1248 //std::ofstream file(tmp.path().c_str());
1250 // assert the directory exists
1251 filesystem::assert_dir(toedit.filepath().dirname());
1253 std::ofstream file(toedit.filepath().c_str());
1255 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1256 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1258 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1259 fit != filerepos.end();
1262 // if the alias is different, dump the original
1263 // if it is the same, dump the provided one
1264 if ( (*fit).alias() != toedit.alias() )
1265 (*fit).dumpRepoOn(file);
1267 newinfo.dumpRepoOn(file);
1272 ////////////////////////////////////////////////////////////////////////////
1274 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1275 const ProgressData::ReceiverFnc & progressrcv )
1277 std::list<RepoInfo> repos = knownRepositories();
1278 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1282 if ( (*it).alias() == alias )
1286 info.setAlias(info.alias());
1287 ZYPP_THROW(RepoNotFoundException(info));
1290 ////////////////////////////////////////////////////////////////////////////
1292 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1293 const url::ViewOption & urlview,
1294 const ProgressData::ReceiverFnc & progressrcv )
1296 std::list<RepoInfo> repos = knownRepositories();
1297 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1301 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1302 urlit != (*it).baseUrlsEnd();
1305 if ((*urlit).asString(urlview) == url.asString(urlview))
1310 info.setAlias(info.alias());
1311 info.setBaseUrl(url);
1312 ZYPP_THROW(RepoNotFoundException(info));
1315 ////////////////////////////////////////////////////////////////////////////
1317 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1319 return str << *obj._pimpl;
1322 /////////////////////////////////////////////////////////////////
1324 ///////////////////////////////////////////////////////////////////