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"
42 #include "zypp/ZYppCallbacks.h"
45 #include "satsolver/pool.h"
46 #include "satsolver/repo.h"
47 #include "satsolver/repo_solv.h"
51 using namespace zypp::repo;
52 using namespace zypp::filesystem;
54 using namespace zypp::repo;
56 ///////////////////////////////////////////////////////////////////
58 { /////////////////////////////////////////////////////////////////
60 ///////////////////////////////////////////////////////////////////
62 // CLASS NAME : RepoManagerOptions
64 ///////////////////////////////////////////////////////////////////
66 RepoManagerOptions::RepoManagerOptions()
68 repoCachePath = ZConfig::instance().repoCachePath();
69 repoRawCachePath = ZConfig::instance().repoMetadataPath();
70 repoPackagesCachePath = ZConfig::instance().repoPackagesPath();
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
94 bool collect( const RepoInfo &repo )
96 repos.push_back(repo);
103 ////////////////////////////////////////////////////////////////////////////
106 * Reads RepoInfo's from a repo file.
108 * \param file pathname of the file to read.
110 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
112 MIL << "repo file: " << file << endl;
113 RepoCollector collector;
114 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
115 return collector.repos;
118 ////////////////////////////////////////////////////////////////////////////
120 std::list<RepoInfo> readRepoFile(const Url & repo_file)
122 // no interface to download a specific file, using workaround:
123 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
125 Pathname path(url.getPathName());
126 url.setPathName ("/");
127 MediaSetAccess access(url);
128 Pathname local = access.provideFile(path);
130 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
132 return repositories_in_file(local);
135 ////////////////////////////////////////////////////////////////////////////
138 * \short List of RepoInfo's from a directory
140 * Goes trough every file ending with ".repo" in a directory and adds all
141 * RepoInfo's contained in that file.
143 * \param dir pathname of the directory to read.
145 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
147 MIL << "directory " << dir << endl;
148 list<RepoInfo> repos;
149 list<Pathname> entries;
150 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
151 ZYPP_THROW(Exception("failed to read directory"));
153 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
154 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
156 if (str::regex_match(it->extension(), allowedRepoExt))
158 list<RepoInfo> tmp = repositories_in_file( *it );
159 repos.insert( repos.end(), tmp.begin(), tmp.end() );
161 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
162 //MIL << "ok" << endl;
168 ////////////////////////////////////////////////////////////////////////////
170 static void assert_alias( const RepoInfo &info )
172 if (info.alias().empty())
173 ZYPP_THROW(RepoNoAliasException());
176 ////////////////////////////////////////////////////////////////////////////
178 static void assert_urls( const RepoInfo &info )
180 if (info.baseUrlsEmpty())
181 ZYPP_THROW(RepoNoUrlException());
184 ////////////////////////////////////////////////////////////////////////////
187 * \short Calculates the raw cache path for a repository
189 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
192 return opt.repoRawCachePath / info.escaped_alias();
196 * \short Calculates the packages cache path for a repository
198 static Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
201 return opt.repoPackagesCachePath / info.escaped_alias();
204 ///////////////////////////////////////////////////////////////////
206 // CLASS NAME : RepoManager::Impl
208 ///////////////////////////////////////////////////////////////////
211 * \short RepoManager implementation.
213 struct RepoManager::Impl
215 Impl( const RepoManagerOptions &opt )
226 RepoManagerOptions options;
228 map<string, RepoInfo> _repoinfos;
231 /** Offer default Impl. */
232 static shared_ptr<Impl> nullimpl()
234 static shared_ptr<Impl> _nullimpl( new Impl );
239 friend Impl * rwcowClone<Impl>( const Impl * rhs );
240 /** clone for RWCOW_pointer */
242 { return new Impl( *this ); }
245 ///////////////////////////////////////////////////////////////////
247 /** \relates RepoManager::Impl Stream output */
248 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
250 return str << "RepoManager::Impl";
253 ///////////////////////////////////////////////////////////////////
255 // CLASS NAME : RepoManager
257 ///////////////////////////////////////////////////////////////////
259 RepoManager::RepoManager( const RepoManagerOptions &opt )
260 : _pimpl( new Impl(opt) )
263 ////////////////////////////////////////////////////////////////////////////
265 RepoManager::~RepoManager()
268 ////////////////////////////////////////////////////////////////////////////
270 std::list<RepoInfo> RepoManager::knownRepositories() const
274 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
276 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
277 for ( RepoInfoList::iterator it = repos.begin();
281 // set the metadata path for the repo
282 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
283 (*it).setMetadataPath(metadata_path);
285 // set the downloaded packages path for the repo
286 Pathname packages_path = packagescache_path_for_repoinfo(_pimpl->options, (*it));
287 (*it).setPackagesPath(packages_path);
292 return std::list<RepoInfo>();
297 ////////////////////////////////////////////////////////////////////////////
299 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
301 return rawcache_path_for_repoinfo(_pimpl->options, info );
304 ////////////////////////////////////////////////////////////////////////////
306 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
308 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
309 RepoType repokind = info.type();
312 switch ( repokind.toEnum() )
314 case RepoType::NONE_e:
315 // unknown, probe the local metadata
316 repokind = probe(rawpath.asUrl());
322 switch ( repokind.toEnum() )
324 case RepoType::RPMMD_e :
326 status = RepoStatus( rawpath + "/repodata/repomd.xml");
330 case RepoType::YAST2_e :
332 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
336 case RepoType::RPMPLAINDIR_e :
338 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
339 status = RepoStatus( rawpath + "/cookie");
343 case RepoType::NONE_e :
344 // Return default RepoStatus in case of RepoType::NONE
345 // indicating it should be created?
346 // ZYPP_THROW(RepoUnknownTypeException());
352 void RepoManager::touchIndexFile(const RepoInfo & info)
354 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
356 RepoType repokind = info.type();
357 if ( repokind.toEnum() == RepoType::NONE_e )
358 // unknown, probe the local metadata
359 repokind = probe(rawpath.asUrl());
360 // if still unknown, just return
361 if (repokind == RepoType::NONE_e)
365 switch ( repokind.toEnum() )
367 case RepoType::RPMMD_e :
368 p = Pathname(rawpath + "/repodata/repomd.xml");
371 case RepoType::YAST2_e :
372 p = Pathname(rawpath + "/content");
375 case RepoType::RPMPLAINDIR_e :
376 p = Pathname(rawpath + "/cookie");
379 case RepoType::NONE_e :
384 // touch the file, ignore error (they are logged anyway)
385 filesystem::touch(p);
388 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
390 RawMetadataRefreshPolicy policy )
394 RepoStatus oldstatus;
395 RepoStatus newstatus;
399 MIL << "Going to try to check whether refresh is needed for " << url << endl;
401 repo::RepoType repokind = info.type();
403 // if the type is unknown, try probing.
404 switch ( repokind.toEnum() )
406 case RepoType::NONE_e:
408 repokind = probe(url);
414 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
415 filesystem::assert_dir(rawpath);
416 oldstatus = metadataStatus(info);
418 // now we've got the old (cached) status, we can decide repo.refresh.delay
419 if (policy != RefreshForced)
421 // difference in seconds
422 double diff = difftime(
423 (Date::ValueType)Date::now(),
424 (Date::ValueType)oldstatus.timestamp()) / 60;
426 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
427 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
428 DBG << "last refresh = " << diff << " minutes ago" << endl;
430 if (diff < ZConfig::instance().repo_refresh_delay())
432 MIL << "Repository '" << info.alias()
433 << "' has been refreshed less than repo.refresh.delay ("
434 << ZConfig::instance().repo_refresh_delay()
435 << ") minutes ago. Advising to skip refresh" << endl;
440 // create temp dir as sibling of rawpath
441 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
443 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
444 ( repokind.toEnum() == RepoType::YAST2_e ) )
446 MediaSetAccess media(url);
447 shared_ptr<repo::Downloader> downloader_ptr;
449 if ( repokind.toEnum() == RepoType::RPMMD_e )
450 downloader_ptr.reset(new yum::Downloader(info.path()));
452 downloader_ptr.reset( new susetags::Downloader(info.path()));
454 RepoStatus newstatus = downloader_ptr->status(media);
455 bool refresh = false;
456 if ( oldstatus.checksum() == newstatus.checksum() )
458 MIL << "repo has not changed" << endl;
459 if ( policy == RefreshForced )
461 MIL << "refresh set to forced" << endl;
467 MIL << "repo has changed, going to refresh" << endl;
472 touchIndexFile(info);
477 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
479 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
480 bool refresh = false;
481 if ( oldstatus.checksum() == newstatus.checksum() )
483 MIL << "repo has not changed" << endl;
484 if ( policy == RefreshForced )
486 MIL << "refresh set to forced" << endl;
492 MIL << "repo has changed, going to refresh" << endl;
497 touchIndexFile(info);
504 ZYPP_THROW(RepoUnknownTypeException());
507 catch ( const Exception &e )
510 ERR << "refresh check failed for " << url << endl;
514 return true; // default
517 void RepoManager::refreshMetadata( const RepoInfo &info,
518 RawMetadataRefreshPolicy policy,
519 const ProgressData::ReceiverFnc & progress )
524 // we will throw this later if no URL checks out fine
525 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
527 // try urls one by one
528 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
534 // check whether to refresh metadata
535 // if the check fails for this url, it throws, so another url will be checked
536 if (!checkIfToRefreshMetadata(info, url, policy))
539 MIL << "Going to refresh metadata from " << url << endl;
541 repo::RepoType repokind = info.type();
543 // if the type is unknown, try probing.
544 switch ( repokind.toEnum() )
546 case RepoType::NONE_e:
548 repokind = probe(*it);
554 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
555 filesystem::assert_dir(rawpath);
557 // create temp dir as sibling of rawpath
558 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
560 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
561 ( repokind.toEnum() == RepoType::YAST2_e ) )
563 MediaSetAccess media(url);
564 shared_ptr<repo::Downloader> downloader_ptr;
566 if ( repokind.toEnum() == RepoType::RPMMD_e )
567 downloader_ptr.reset(new yum::Downloader(info.path()));
569 downloader_ptr.reset( new susetags::Downloader(info.path()));
572 * Given a downloader, sets the other repos raw metadata
573 * path as cache paths for the fetcher, so if another
574 * repo has the same file, it will not download it
575 * but copy it from the other repository
577 std::list<RepoInfo> repos = knownRepositories();
578 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
582 Pathname cachepath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
583 if ( PathInfo(cachepath).isExist() )
584 downloader_ptr->addCachePath(cachepath);
587 downloader_ptr->download( media, tmpdir.path());
590 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
592 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
594 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
596 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
599 file << newstatus.checksum() << endl;
606 ZYPP_THROW(RepoUnknownTypeException());
609 // ok we have the metadata, now exchange
612 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
613 filesystem::rename( rawpath, oldmetadata.path() );
614 // move the just downloaded there
615 filesystem::rename( tmpdir.path(), rawpath );
620 catch ( const Exception &e )
623 ERR << "Trying another url..." << endl;
625 // remember the exception caught for the *first URL*
626 // if all other URLs fail, the rexception will be thrown with the
627 // cause of the problem of the first URL remembered
628 if (it == info.baseUrlsBegin())
629 rexception.remember(e);
632 ERR << "No more urls..." << endl;
633 ZYPP_THROW(rexception);
636 ////////////////////////////////////////////////////////////////////////////
638 void RepoManager::cleanMetadata( const RepoInfo &info,
639 const ProgressData::ReceiverFnc & progressfnc )
641 ProgressData progress(100);
642 progress.sendTo(progressfnc);
644 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
648 void RepoManager::cleanPackages( const RepoInfo &info,
649 const ProgressData::ReceiverFnc & progressfnc )
651 ProgressData progress(100);
652 progress.sendTo(progressfnc);
654 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
658 void RepoManager::buildCache( const RepoInfo &info,
659 CacheBuildPolicy policy,
660 const ProgressData::ReceiverFnc & progressrcv )
663 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
665 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
666 Pathname solvfile = base.extend(".solv");
669 RepoStatus raw_metadata_status = metadataStatus(info);
670 if ( raw_metadata_status.empty() )
672 /* if there is no cache at this point, we refresh the raw
673 in case this is the first time - if it's !autorefresh,
674 we may still refresh */
675 refreshMetadata(info, RefreshIfNeeded, progressrcv );
676 raw_metadata_status = metadataStatus(info);
679 bool needs_cleaning = false;
680 if ( isCached( info ) )
682 MIL << info.alias() << " is already cached." << endl;
683 //data::RecordId id = store.lookupRepository(info.alias());
684 RepoStatus cache_status = cacheStatus(info);
686 if ( cache_status.checksum() == raw_metadata_status.checksum() )
688 MIL << info.alias() << " cache is up to date with metadata." << endl;
689 if ( policy == BuildIfNeeded ) {
693 MIL << info.alias() << " cache rebuild is forced" << endl;
697 needs_cleaning = true;
700 ProgressData progress(100);
701 callback::SendReport<ProgressReport> report;
702 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
703 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
711 MIL << info.alias() << " building cache..." << endl;
713 repo::RepoType repokind = info.type();
715 // if the type is unknown, try probing.
716 switch ( repokind.toEnum() )
718 case RepoType::NONE_e:
719 // unknown, probe the local metadata
720 repokind = probe(rawpath.asUrl());
726 MIL << "repo type is " << repokind << endl;
728 switch ( repokind.toEnum() )
730 case RepoType::RPMMD_e :
731 case RepoType::YAST2_e :
733 // Take care we unlink the solvfile on exception
734 ManagedFile guard( solvfile, filesystem::unlink );
737 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() );
739 MIL << "Executing: " << cmd.str() << endl;
740 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
743 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
744 WAR << " " << output;
745 cmd << " " << output;
748 int ret = prog.close();
751 RepoException ex(str::form("Failed to cache repo (%d).", ret));
752 ex.remember( cmd.str() );
757 guard.resetDispose();
761 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
765 switch ( repokind.toEnum() )
767 case RepoType::RPMMD_e :
770 CombinedProgressData subprogrcv( progress, 100);
771 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
772 parser.parse(rawpath);
776 case RepoType::YAST2_e :
779 CombinedProgressData subprogrcv( progress, 100);
780 parser::susetags::RepoParser parser(id, store, subprogrcv);
781 parser.parse(rawpath);
787 case RepoType::RPMPLAINDIR_e :
789 CombinedProgressData subprogrcv( progress, 100);
790 InputStream is(rawpath + "cookie");
792 getline( is.stream(), buffer);
794 parser::plaindir::RepoParser parser(id, store, subprogrcv);
795 parser.parse(url.getPathName());
800 ZYPP_THROW(RepoUnknownTypeException());
803 // update timestamp and checksum
804 //store.updateRepositoryStatus(id, raw_metadata_status);
805 setCacheStatus(info.escaped_alias(), raw_metadata_status);
806 MIL << "Commit cache.." << endl;
811 ////////////////////////////////////////////////////////////////////////////
813 repo::RepoType RepoManager::probe( const Url &url ) const
815 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
817 // Handle non existing local directory in advance, as
818 // MediaSetAccess does not support it.
819 return repo::RepoType::NONE;
824 MediaSetAccess access(url);
825 if ( access.doesFileExist("/repodata/repomd.xml") )
826 return repo::RepoType::RPMMD;
827 if ( access.doesFileExist("/content") )
828 return repo::RepoType::YAST2;
830 // if it is a local url of type dir
831 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
833 Pathname path = Pathname(url.getPathName());
834 if ( PathInfo(path).isDir() )
836 // allow empty dirs for now
837 return repo::RepoType::RPMPLAINDIR;
841 catch ( const media::MediaException &e )
844 RepoException enew("Error trying to read from " + url.asString());
848 catch ( const Exception &e )
851 Exception enew("Unknown error reading from " + url.asString());
856 return repo::RepoType::NONE;
859 ////////////////////////////////////////////////////////////////////////////
861 void RepoManager::cleanCache( const RepoInfo &info,
862 const ProgressData::ReceiverFnc & progressrcv )
864 ProgressData progress(100);
865 progress.sendTo(progressrcv);
868 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".solv"));
870 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".cookie"));
875 void RepoManager::cleanTargetCache(const ProgressData::ReceiverFnc & progressrcv)
877 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".solv"));
878 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".cookie"));
881 ////////////////////////////////////////////////////////////////////////////
883 bool RepoManager::isCached( const RepoInfo &info ) const
885 Pathname name = _pimpl->options.repoCachePath;
886 return PathInfo(name + Pathname(info.escaped_alias()).extend(".solv")).isExist();
889 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
892 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
893 Pathname cookiefile = base.extend(".cookie");
895 return RepoStatus::fromCookieFile(cookiefile);
898 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
900 Pathname base = _pimpl->options.repoCachePath + alias;
901 Pathname cookiefile = base.extend(".cookie");
903 status.saveToCookieFile(cookiefile);
906 void RepoManager::loadFromCache( const RepoInfo & info,
907 const ProgressData::ReceiverFnc & progressrcv )
910 string alias = info.escaped_alias();
911 Pathname solvfile = (_pimpl->options.repoCachePath / alias).extend(".solv");
913 if ( ! PathInfo(solvfile).isExist() )
914 ZYPP_THROW(RepoNotCachedException());
918 sat::Pool::instance().addRepoSolv( solvfile, info );
920 catch ( const Exception & exp )
923 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
924 cleanCache( info, progressrcv );
925 buildCache( info, BuildIfNeeded, progressrcv );
927 sat::Pool::instance().addRepoSolv( solvfile, info );
931 ////////////////////////////////////////////////////////////////////////////
934 * Generate a non existing filename in a directory, using a base
935 * name. For example if a directory contains 3 files
941 * If you try to generate a unique filename for this directory,
942 * based on "ruu" you will get "ruu", but if you use the base
943 * "foo" you will get "foo_1"
945 * \param dir Directory where the file needs to be unique
946 * \param basefilename string to base the filename on.
948 static Pathname generate_non_existing_name( const Pathname &dir,
949 const std::string &basefilename )
951 string final_filename = basefilename;
953 while ( PathInfo(dir + final_filename).isExist() )
955 final_filename = basefilename + "_" + str::numstring(counter);
958 return dir + Pathname(final_filename);
961 ////////////////////////////////////////////////////////////////////////////
964 * \short Generate a related filename from a repo info
966 * From a repo info, it will try to use the alias as a filename
967 * escaping it if necessary. Other fallbacks can be added to
968 * this function in case there is no way to use the alias
970 static std::string generate_filename( const RepoInfo &info )
974 std::string filename = info.alias();
975 // replace slashes with underscores
976 size_t pos = filename.find(fnd);
977 while(pos!=string::npos)
979 filename.replace(pos,fnd.length(),rep);
980 pos = filename.find(fnd,pos+rep.length());
982 filename = Pathname(filename).extend(".repo").asString();
983 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
988 ////////////////////////////////////////////////////////////////////////////
990 void RepoManager::addRepository( const RepoInfo &info,
991 const ProgressData::ReceiverFnc & progressrcv )
995 ProgressData progress(100);
996 callback::SendReport<ProgressReport> report;
997 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
998 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1001 std::list<RepoInfo> repos = knownRepositories();
1002 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1006 if ( info.alias() == (*it).alias() )
1007 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
1010 RepoInfo tosave = info;
1012 // check the first url for now
1013 if ( ZConfig::instance().repo_add_probe()
1014 || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
1016 DBG << "unknown repository type, probing" << endl;
1018 RepoType probedtype;
1019 probedtype = probe(*tosave.baseUrlsBegin());
1020 if ( tosave.baseUrlsSize() > 0 )
1022 if ( probedtype == RepoType::NONE )
1023 ZYPP_THROW(RepoUnknownTypeException());
1025 tosave.setType(probedtype);
1031 // assert the directory exists
1032 filesystem::assert_dir(_pimpl->options.knownReposPath);
1034 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1035 generate_filename(tosave));
1036 // now we have a filename that does not exists
1037 MIL << "Saving repo in " << repofile << endl;
1039 std::ofstream file(repofile.c_str());
1041 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1044 tosave.dumpRepoOn(file);
1046 MIL << "done" << endl;
1049 void RepoManager::addRepositories( const Url &url,
1050 const ProgressData::ReceiverFnc & progressrcv )
1052 std::list<RepoInfo> knownrepos = knownRepositories();
1053 std::list<RepoInfo> repos = readRepoFile(url);
1054 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1058 // look if the alias is in the known repos.
1059 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1060 kit != knownrepos.end();
1063 if ( (*it).alias() == (*kit).alias() )
1065 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1066 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1071 string filename = Pathname(url.getPathName()).basename();
1073 if ( filename == Pathname() )
1074 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1076 // assert the directory exists
1077 filesystem::assert_dir(_pimpl->options.knownReposPath);
1079 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1080 // now we have a filename that does not exists
1081 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1083 std::ofstream file(repofile.c_str());
1085 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1088 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1092 MIL << "Saving " << (*it).alias() << endl;
1093 (*it).dumpRepoOn(file);
1095 MIL << "done" << endl;
1098 ////////////////////////////////////////////////////////////////////////////
1100 void RepoManager::removeRepository( const RepoInfo & info,
1101 const ProgressData::ReceiverFnc & progressrcv)
1103 ProgressData progress;
1104 callback::SendReport<ProgressReport> report;
1105 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1106 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1108 MIL << "Going to delete repo " << info.alias() << endl;
1110 std::list<RepoInfo> repos = knownRepositories();
1111 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1115 // they can be the same only if the provided is empty, that means
1116 // the provided repo has no alias
1118 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1121 // TODO match by url
1123 // we have a matcing repository, now we need to know
1124 // where it does come from.
1125 RepoInfo todelete = *it;
1126 if (todelete.filepath().empty())
1128 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1132 // figure how many repos are there in the file:
1133 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1134 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1136 // easy, only this one, just delete the file
1137 if ( filesystem::unlink(todelete.filepath()) != 0 )
1139 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1141 MIL << todelete.alias() << " sucessfully deleted." << endl;
1145 // there are more repos in the same file
1146 // write them back except the deleted one.
1148 //std::ofstream file(tmp.path().c_str());
1150 // assert the directory exists
1151 filesystem::assert_dir(todelete.filepath().dirname());
1153 std::ofstream file(todelete.filepath().c_str());
1155 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1156 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1158 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1159 fit != filerepos.end();
1162 if ( (*fit).alias() != todelete.alias() )
1163 (*fit).dumpRepoOn(file);
1167 CombinedProgressData subprogrcv(progress, 70);
1168 CombinedProgressData cleansubprogrcv(progress, 30);
1169 // now delete it from cache
1170 if ( isCached(todelete) )
1171 cleanCache( todelete, subprogrcv);
1172 // now delete metadata (#301037)
1173 cleanMetadata( todelete, cleansubprogrcv);
1174 MIL << todelete.alias() << " sucessfully deleted." << endl;
1176 } // else filepath is empty
1179 // should not be reached on a sucess workflow
1180 ZYPP_THROW(RepoNotFoundException(info));
1183 ////////////////////////////////////////////////////////////////////////////
1185 void RepoManager::modifyRepository( const std::string &alias,
1186 const RepoInfo & newinfo,
1187 const ProgressData::ReceiverFnc & progressrcv )
1189 RepoInfo toedit = getRepositoryInfo(alias);
1191 // check if the new alias already exists when renaming the repo
1192 if (alias != newinfo.alias())
1194 std::list<RepoInfo> repos = knownRepositories();
1195 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1199 if ( newinfo.alias() == (*it).alias() )
1200 ZYPP_THROW(RepoAlreadyExistsException(newinfo.alias()));
1204 if (toedit.filepath().empty())
1206 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1210 // figure how many repos are there in the file:
1211 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1213 // there are more repos in the same file
1214 // write them back except the deleted one.
1216 //std::ofstream file(tmp.path().c_str());
1218 // assert the directory exists
1219 filesystem::assert_dir(toedit.filepath().dirname());
1221 std::ofstream file(toedit.filepath().c_str());
1223 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1224 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1226 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1227 fit != filerepos.end();
1230 // if the alias is different, dump the original
1231 // if it is the same, dump the provided one
1232 if ( (*fit).alias() != toedit.alias() )
1233 (*fit).dumpRepoOn(file);
1235 newinfo.dumpRepoOn(file);
1240 ////////////////////////////////////////////////////////////////////////////
1242 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1243 const ProgressData::ReceiverFnc & progressrcv )
1245 std::list<RepoInfo> repos = knownRepositories();
1246 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1250 if ( (*it).alias() == alias )
1254 info.setAlias(info.alias());
1255 ZYPP_THROW(RepoNotFoundException(info));
1258 ////////////////////////////////////////////////////////////////////////////
1260 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1261 const url::ViewOption & urlview,
1262 const ProgressData::ReceiverFnc & progressrcv )
1264 std::list<RepoInfo> repos = knownRepositories();
1265 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1269 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1270 urlit != (*it).baseUrlsEnd();
1273 if ((*urlit).asString(urlview) == url.asString(urlview))
1278 info.setAlias(info.alias());
1279 info.setBaseUrl(url);
1280 ZYPP_THROW(RepoNotFoundException(info));
1283 ////////////////////////////////////////////////////////////////////////////
1285 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1287 return str << *obj._pimpl;
1290 /////////////////////////////////////////////////////////////////
1292 ///////////////////////////////////////////////////////////////////