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/cache/SolvStore.h"
32 #include "zypp/media/MediaManager.h"
33 #include "zypp/MediaSetAccess.h"
34 #include "zypp/ExternalProgram.h"
35 #include "zypp/ManagedFile.h"
37 #include "zypp/parser/RepoFileReader.h"
38 #include "zypp/repo/yum/Downloader.h"
39 #include "zypp/parser/yum/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;
131 // CombinedProgressData subprogrcv(progress);
133 // store.cleanRepository(info.alias(), subprogrcv);
136 ////////////////////////////////////////////////////////////////////////////
139 * Reads RepoInfo's from a repo file.
141 * \param file pathname of the file to read.
143 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
145 MIL << "repo file: " << file << endl;
146 RepoCollector collector;
147 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
148 return collector.repos;
151 ////////////////////////////////////////////////////////////////////////////
153 std::list<RepoInfo> readRepoFile(const Url & repo_file)
155 // no interface to download a specific file, using workaround:
156 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
158 Pathname path(url.getPathName());
159 url.setPathName ("/");
160 MediaSetAccess access(url);
161 Pathname local = access.provideFile(path);
163 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
165 return repositories_in_file(local);
168 ////////////////////////////////////////////////////////////////////////////
171 * \short List of RepoInfo's from a directory
173 * Goes trough every file ending with ".repo" in a directory and adds all
174 * RepoInfo's contained in that file.
176 * \param dir pathname of the directory to read.
178 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
180 MIL << "directory " << dir << endl;
181 list<RepoInfo> repos;
182 list<Pathname> entries;
183 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
184 ZYPP_THROW(Exception("failed to read directory"));
186 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
187 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
189 if (str::regex_match(it->extension(), allowedRepoExt))
191 list<RepoInfo> tmp = repositories_in_file( *it );
192 repos.insert( repos.end(), tmp.begin(), tmp.end() );
194 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
195 //MIL << "ok" << endl;
201 ////////////////////////////////////////////////////////////////////////////
203 static void assert_alias( const RepoInfo &info )
205 if (info.alias().empty())
206 ZYPP_THROW(RepoNoAliasException());
209 ////////////////////////////////////////////////////////////////////////////
211 static void assert_urls( const RepoInfo &info )
213 if (info.baseUrlsEmpty())
214 ZYPP_THROW(RepoNoUrlException());
217 ////////////////////////////////////////////////////////////////////////////
220 * \short Calculates the raw cache path for a repository
222 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
225 return opt.repoRawCachePath + info.alias();
228 ///////////////////////////////////////////////////////////////////
230 // CLASS NAME : RepoManager::Impl
232 ///////////////////////////////////////////////////////////////////
235 * \short RepoManager implementation.
237 struct RepoManager::Impl
239 Impl( const RepoManagerOptions &opt )
250 RepoManagerOptions options;
252 map<string, RepoInfo> _repoinfos;
255 /** Offer default Impl. */
256 static shared_ptr<Impl> nullimpl()
258 static shared_ptr<Impl> _nullimpl( new Impl );
263 friend Impl * rwcowClone<Impl>( const Impl * rhs );
264 /** clone for RWCOW_pointer */
266 { return new Impl( *this ); }
269 ///////////////////////////////////////////////////////////////////
271 /** \relates RepoManager::Impl Stream output */
272 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
274 return str << "RepoManager::Impl";
277 ///////////////////////////////////////////////////////////////////
279 // CLASS NAME : RepoManager
281 ///////////////////////////////////////////////////////////////////
283 RepoManager::RepoManager( const RepoManagerOptions &opt )
284 : _pimpl( new Impl(opt) )
287 ////////////////////////////////////////////////////////////////////////////
289 RepoManager::~RepoManager()
292 ////////////////////////////////////////////////////////////////////////////
294 std::list<RepoInfo> RepoManager::knownRepositories() const
298 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
300 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
301 for ( RepoInfoList::iterator it = repos.begin();
305 // set the metadata path for the repo
306 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
307 (*it).setMetadataPath(metadata_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 // the order of RepoStatus && RepoStatus matters! (#304310)
353 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
357 case RepoType::RPMPLAINDIR_e :
359 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
360 status = RepoStatus( rawpath + "/cookie");
364 case RepoType::NONE_e :
365 // Return default RepoStatus in case of RepoType::NONE
366 // indicating it should be created?
367 // ZYPP_THROW(RepoUnknownTypeException());
373 void RepoManager::touchIndexFile(const RepoInfo & info)
375 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
377 RepoType repokind = info.type();
378 if ( repokind.toEnum() == RepoType::NONE_e )
379 // unknown, probe the local metadata
380 repokind = probe(rawpath.asUrl());
381 // if still unknown, just return
382 if (repokind == RepoType::NONE_e)
386 switch ( repokind.toEnum() )
388 case RepoType::RPMMD_e :
389 p = Pathname(rawpath + "/repodata/repomd.xml");
392 case RepoType::YAST2_e :
393 p = Pathname(rawpath + "/content");
396 case RepoType::RPMPLAINDIR_e :
397 p = Pathname(rawpath + "/cookie");
400 case RepoType::NONE_e :
405 // touch the file, ignore error (they are logged anyway)
406 filesystem::touch(p);
409 bool RepoManager::checkIfToRefreshMetadata( 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)
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;
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);
498 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
500 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
501 bool refresh = false;
502 if ( oldstatus.checksum() == newstatus.checksum() )
504 MIL << "repo has not changed" << endl;
505 if ( policy == RefreshForced )
507 MIL << "refresh set to forced" << endl;
513 MIL << "repo has changed, going to refresh" << endl;
518 touchIndexFile(info);
525 ZYPP_THROW(RepoUnknownTypeException());
528 catch ( const Exception &e )
531 ERR << "refresh check failed for " << url << endl;
535 return true; // default
538 void RepoManager::refreshMetadata( const RepoInfo &info,
539 RawMetadataRefreshPolicy policy,
540 const ProgressData::ReceiverFnc & progress )
545 // we will throw this later if no URL checks out fine
546 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
548 // try urls one by one
549 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
555 // check whether to refresh metadata
556 // if the check fails for this url, it throws, so another url will be checked
557 if (!checkIfToRefreshMetadata(info, url, policy))
560 MIL << "Going to refresh metadata from " << url << endl;
562 repo::RepoType repokind = info.type();
564 // if the type is unknown, try probing.
565 switch ( repokind.toEnum() )
567 case RepoType::NONE_e:
569 repokind = probe(*it);
575 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
576 filesystem::assert_dir(rawpath);
578 // create temp dir as sibling of rawpath
579 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
581 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
582 ( repokind.toEnum() == RepoType::YAST2_e ) )
584 MediaSetAccess media(url);
585 shared_ptr<repo::Downloader> downloader_ptr;
587 if ( repokind.toEnum() == RepoType::RPMMD_e )
588 downloader_ptr.reset(new yum::Downloader(info.path()));
590 downloader_ptr.reset( new susetags::Downloader(info.path()));
593 * Given a downloader, sets the other repos raw metadata
594 * path as cache paths for the fetcher, so if another
595 * repo has the same file, it will not download it
596 * but copy it from the other repository
598 std::list<RepoInfo> repos = knownRepositories();
599 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
603 downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
606 downloader_ptr->download( media, tmpdir.path());
609 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
611 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
613 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
615 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
618 file << newstatus.checksum() << endl;
625 ZYPP_THROW(RepoUnknownTypeException());
628 // ok we have the metadata, now exchange
630 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
631 filesystem::rename( rawpath, oldmetadata.path() );
632 // move the just downloaded there
633 filesystem::rename( tmpdir.path(), rawpath );
637 catch ( const Exception &e )
640 ERR << "Trying another url..." << endl;
642 // remember the exception caught for the *first URL*
643 // if all other URLs fail, the rexception will be thrown with the
644 // cause of the problem of the first URL remembered
645 if (it == info.baseUrlsBegin())
646 rexception.remember(e);
649 ERR << "No more urls..." << endl;
650 ZYPP_THROW(rexception);
653 ////////////////////////////////////////////////////////////////////////////
655 void RepoManager::cleanMetadata( const RepoInfo &info,
656 const ProgressData::ReceiverFnc & progressfnc )
658 ProgressData progress(100);
659 progress.sendTo(progressfnc);
661 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
665 void RepoManager::buildCache( const RepoInfo &info,
666 CacheBuildPolicy policy,
667 const ProgressData::ReceiverFnc & progressrcv )
670 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
672 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
673 Pathname solvfile = base.extend(".solv");
675 //cache::SolvStore store(_pimpl->options.repoCachePath);
677 RepoStatus raw_metadata_status = metadataStatus(info);
678 if ( raw_metadata_status.empty() )
680 ZYPP_THROW(RepoMetadataException(info));
683 bool needs_cleaning = false;
684 if ( isCached( info ) )
686 MIL << info.alias() << " is already cached." << endl;
687 //data::RecordId id = store.lookupRepository(info.alias());
688 RepoStatus cache_status = cacheStatus(info);
690 if ( cache_status.checksum() == raw_metadata_status.checksum() )
692 MIL << info.alias() << " cache is up to date with metadata." << endl;
693 if ( policy == BuildIfNeeded ) {
697 MIL << info.alias() << " cache rebuild is forced" << endl;
701 needs_cleaning = true;
704 ProgressData progress(100);
705 callback::SendReport<ProgressReport> report;
706 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
707 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
712 // Pathname name = _pimpl->options.repoCachePath;
713 // //data::RecordId id = store.lookupRepository(info.alias());
716 // name += os.str() + ".solv";
718 // cleanCacheInternal( store, info);
722 MIL << info.alias() << " building cache..." << endl;
723 //data::RecordId id = store.lookupOrAppendRepository(info.alias());
725 repo::RepoType repokind = info.type();
727 // if the type is unknown, try probing.
728 switch ( repokind.toEnum() )
730 case RepoType::NONE_e:
731 // unknown, probe the local metadata
732 repokind = probe(rawpath.asUrl());
738 MIL << "repo type is " << repokind << endl;
740 switch ( repokind.toEnum() )
742 case RepoType::RPMMD_e :
743 case RepoType::YAST2_e :
745 MIL << "Executing solv converter" << endl;
746 // Take care we unlink the solvfile on exception
747 ManagedFile guard( solvfile, filesystem::unlink );
749 string cmd( str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() ) );
750 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
751 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
752 MIL << " " << output;
754 int ret = prog.close();
756 ZYPP_THROW(RepoUnknownTypeException());
759 guard.resetDispose();
763 ZYPP_THROW(Exception("Unhandled repostory type"));
767 switch ( repokind.toEnum() )
769 case RepoType::RPMMD_e :
772 CombinedProgressData subprogrcv( progress, 100);
773 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
774 parser.parse(rawpath);
778 case RepoType::YAST2_e :
781 CombinedProgressData subprogrcv( progress, 100);
782 parser::susetags::RepoParser parser(id, store, subprogrcv);
783 parser.parse(rawpath);
789 case RepoType::RPMPLAINDIR_e :
791 CombinedProgressData subprogrcv( progress, 100);
792 InputStream is(rawpath + "cookie");
794 getline( is.stream(), buffer);
796 parser::plaindir::RepoParser parser(id, store, subprogrcv);
797 parser.parse(url.getPathName());
802 ZYPP_THROW(RepoUnknownTypeException());
805 // update timestamp and checksum
806 //store.updateRepositoryStatus(id, raw_metadata_status);
807 setCacheStatus(info.escaped_alias(), raw_metadata_status);
808 MIL << "Commit cache.." << endl;
813 ////////////////////////////////////////////////////////////////////////////
815 repo::RepoType RepoManager::probe( const Url &url ) const
817 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
819 // Handle non existing local directory in advance, as
820 // MediaSetAccess does not support it.
821 return repo::RepoType::NONE;
826 MediaSetAccess access(url);
827 if ( access.doesFileExist("/repodata/repomd.xml") )
828 return repo::RepoType::RPMMD;
829 if ( access.doesFileExist("/content") )
830 return repo::RepoType::YAST2;
832 // if it is a local url of type dir
833 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
835 Pathname path = Pathname(url.getPathName());
836 if ( PathInfo(path).isDir() )
838 // allow empty dirs for now
839 return repo::RepoType::RPMPLAINDIR;
843 catch ( const media::MediaException &e )
846 RepoException enew("Error trying to read from " + url.asString());
850 catch ( const Exception &e )
853 Exception enew("Unknown error reading from " + url.asString());
858 return repo::RepoType::NONE;
861 ////////////////////////////////////////////////////////////////////////////
863 void RepoManager::cleanCache( const RepoInfo &info,
864 const ProgressData::ReceiverFnc & progressrcv )
866 Pathname name = _pimpl->options.repoCachePath;
867 name += info.escaped_alias() + ".solv";
871 ////////////////////////////////////////////////////////////////////////////
873 bool RepoManager::isCached( const RepoInfo &info ) const
875 Pathname name = _pimpl->options.repoCachePath;
876 return PathInfo(name + Pathname(info.escaped_alias()).extend(".solv")).isExist();
879 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
882 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
883 Pathname cookiefile = base.extend(".cookie");
885 return RepoStatus::fromCookieFile(cookiefile);
888 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
890 Pathname base = _pimpl->options.repoCachePath + alias;
891 Pathname cookiefile = base.extend(".cookie");
893 status.saveToCookieFile(cookiefile);
896 void RepoManager::loadFromCache( const RepoInfo &info,
897 const ProgressData::ReceiverFnc & progressrcv )
900 sat::Pool satpool( sat::Pool::instance() );
901 string alias = info.escaped_alias();
903 Pathname solvfile = (_pimpl->options.repoCachePath + alias).extend(".solv");
905 if ( ! PathInfo(solvfile).isExist() )
906 ZYPP_THROW(RepoNotCachedException());
908 sat::Repo repo = satpool.addRepoSolv(solvfile, info);
911 ////////////////////////////////////////////////////////////////////////////
914 * Generate a non existing filename in a directory, using a base
915 * name. For example if a directory contains 3 files
921 * If you try to generate a unique filename for this directory,
922 * based on "ruu" you will get "ruu", but if you use the base
923 * "foo" you will get "foo_1"
925 * \param dir Directory where the file needs to be unique
926 * \param basefilename string to base the filename on.
928 static Pathname generate_non_existing_name( const Pathname &dir,
929 const std::string &basefilename )
931 string final_filename = basefilename;
933 while ( PathInfo(dir + final_filename).isExist() )
935 final_filename = basefilename + "_" + str::numstring(counter);
938 return dir + Pathname(final_filename);
941 ////////////////////////////////////////////////////////////////////////////
944 * \short Generate a related filename from a repo info
946 * From a repo info, it will try to use the alias as a filename
947 * escaping it if necessary. Other fallbacks can be added to
948 * this function in case there is no way to use the alias
950 static std::string generate_filename( const RepoInfo &info )
954 std::string filename = info.alias();
955 // replace slashes with underscores
956 size_t pos = filename.find(fnd);
957 while(pos!=string::npos)
959 filename.replace(pos,fnd.length(),rep);
960 pos = filename.find(fnd,pos+rep.length());
962 filename = Pathname(filename).extend(".repo").asString();
963 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
968 ////////////////////////////////////////////////////////////////////////////
970 void RepoManager::addRepository( const RepoInfo &info,
971 const ProgressData::ReceiverFnc & progressrcv )
975 ProgressData progress(100);
976 callback::SendReport<ProgressReport> report;
977 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
978 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
981 std::list<RepoInfo> repos = knownRepositories();
982 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
986 if ( info.alias() == (*it).alias() )
987 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
990 RepoInfo tosave = info;
992 // check the first url for now
993 if ( ZConfig::instance().repo_add_probe()
994 || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
996 DBG << "unknown repository type, probing" << endl;
999 probedtype = probe(*tosave.baseUrlsBegin());
1000 if ( tosave.baseUrlsSize() > 0 )
1002 if ( probedtype == RepoType::NONE )
1003 ZYPP_THROW(RepoUnknownTypeException());
1005 tosave.setType(probedtype);
1011 // assert the directory exists
1012 filesystem::assert_dir(_pimpl->options.knownReposPath);
1014 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1015 generate_filename(tosave));
1016 // now we have a filename that does not exists
1017 MIL << "Saving repo in " << repofile << endl;
1019 std::ofstream file(repofile.c_str());
1021 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1024 tosave.dumpRepoOn(file);
1026 MIL << "done" << endl;
1029 void RepoManager::addRepositories( const Url &url,
1030 const ProgressData::ReceiverFnc & progressrcv )
1032 std::list<RepoInfo> knownrepos = knownRepositories();
1033 std::list<RepoInfo> repos = readRepoFile(url);
1034 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1038 // look if the alias is in the known repos.
1039 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1040 kit != knownrepos.end();
1043 if ( (*it).alias() == (*kit).alias() )
1045 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1046 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1051 string filename = Pathname(url.getPathName()).basename();
1053 if ( filename == Pathname() )
1054 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1056 // assert the directory exists
1057 filesystem::assert_dir(_pimpl->options.knownReposPath);
1059 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1060 // now we have a filename that does not exists
1061 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1063 std::ofstream file(repofile.c_str());
1065 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1068 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1072 MIL << "Saving " << (*it).alias() << endl;
1073 (*it).dumpRepoOn(file);
1075 MIL << "done" << endl;
1078 ////////////////////////////////////////////////////////////////////////////
1080 void RepoManager::removeRepository( const RepoInfo & info,
1081 const ProgressData::ReceiverFnc & progressrcv)
1083 ProgressData progress;
1084 callback::SendReport<ProgressReport> report;
1085 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1086 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1088 MIL << "Going to delete repo " << info.alias() << endl;
1090 std::list<RepoInfo> repos = knownRepositories();
1091 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1095 // they can be the same only if the provided is empty, that means
1096 // the provided repo has no alias
1098 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1101 // TODO match by url
1103 // we have a matcing repository, now we need to know
1104 // where it does come from.
1105 RepoInfo todelete = *it;
1106 if (todelete.filepath().empty())
1108 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1112 // figure how many repos are there in the file:
1113 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1114 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1116 // easy, only this one, just delete the file
1117 if ( filesystem::unlink(todelete.filepath()) != 0 )
1119 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1121 MIL << todelete.alias() << " sucessfully deleted." << endl;
1125 // there are more repos in the same file
1126 // write them back except the deleted one.
1128 //std::ofstream file(tmp.path().c_str());
1130 // assert the directory exists
1131 filesystem::assert_dir(todelete.filepath().dirname());
1133 std::ofstream file(todelete.filepath().c_str());
1135 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1136 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1138 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1139 fit != filerepos.end();
1142 if ( (*fit).alias() != todelete.alias() )
1143 (*fit).dumpRepoOn(file);
1147 CombinedProgressData subprogrcv(progress, 70);
1148 CombinedProgressData cleansubprogrcv(progress, 30);
1149 // now delete it from cache
1150 if ( isCached(todelete) )
1151 cleanCache( todelete, subprogrcv);
1152 // now delete metadata (#301037)
1153 cleanMetadata( todelete, cleansubprogrcv);
1154 MIL << todelete.alias() << " sucessfully deleted." << endl;
1156 } // else filepath is empty
1159 // should not be reached on a sucess workflow
1160 ZYPP_THROW(RepoNotFoundException(info));
1163 ////////////////////////////////////////////////////////////////////////////
1165 void RepoManager::modifyRepository( const std::string &alias,
1166 const RepoInfo & newinfo,
1167 const ProgressData::ReceiverFnc & progressrcv )
1169 RepoInfo toedit = getRepositoryInfo(alias);
1171 if (toedit.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(toedit.filepath());
1180 // there are more repos in the same file
1181 // write them back except the deleted one.
1183 //std::ofstream file(tmp.path().c_str());
1185 // assert the directory exists
1186 filesystem::assert_dir(toedit.filepath().dirname());
1188 std::ofstream file(toedit.filepath().c_str());
1190 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1191 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1193 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1194 fit != filerepos.end();
1197 // if the alias is different, dump the original
1198 // if it is the same, dump the provided one
1199 if ( (*fit).alias() != toedit.alias() )
1200 (*fit).dumpRepoOn(file);
1202 newinfo.dumpRepoOn(file);
1207 ////////////////////////////////////////////////////////////////////////////
1209 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1210 const ProgressData::ReceiverFnc & progressrcv )
1212 std::list<RepoInfo> repos = knownRepositories();
1213 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1217 if ( (*it).alias() == alias )
1221 info.setAlias(info.alias());
1222 ZYPP_THROW(RepoNotFoundException(info));
1225 ////////////////////////////////////////////////////////////////////////////
1227 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1228 const url::ViewOption & urlview,
1229 const ProgressData::ReceiverFnc & progressrcv )
1231 std::list<RepoInfo> repos = knownRepositories();
1232 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1236 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1237 urlit != (*it).baseUrlsEnd();
1240 if ((*urlit).asString(urlview) == url.asString(urlview))
1245 info.setAlias(info.alias());
1246 info.setBaseUrl(url);
1247 ZYPP_THROW(RepoNotFoundException(info));
1250 ////////////////////////////////////////////////////////////////////////////
1252 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1254 return str << *obj._pimpl;
1257 /////////////////////////////////////////////////////////////////
1259 ///////////////////////////////////////////////////////////////////