1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/RepoManager.cc
20 #include "zypp/base/InputStream.h"
21 #include "zypp/base/Logger.h"
22 #include "zypp/base/Gettext.h"
23 #include "zypp/base/Function.h"
24 #include "zypp/base/Regex.h"
25 #include "zypp/PathInfo.h"
26 #include "zypp/TmpPath.h"
28 #include "zypp/repo/RepoException.h"
29 #include "zypp/RepoManager.h"
31 #include "zypp/media/MediaManager.h"
32 #include "zypp/MediaSetAccess.h"
33 #include "zypp/ExternalProgram.h"
34 #include "zypp/ManagedFile.h"
36 #include "zypp/parser/RepoFileReader.h"
37 #include "zypp/repo/yum/Downloader.h"
38 #include "zypp/parser/yum/RepoParser.h"
39 #include "zypp/repo/susetags/Downloader.h"
40 #include "zypp/parser/susetags/RepoParser.h"
41 #include "zypp/parser/plaindir/RepoParser.h"
43 #include "zypp/ZYppCallbacks.h"
46 #include "satsolver/pool.h"
47 #include "satsolver/repo.h"
48 #include "satsolver/repo_solv.h"
52 using namespace zypp::repo;
53 using namespace zypp::filesystem;
55 using namespace zypp::repo;
57 ///////////////////////////////////////////////////////////////////
59 { /////////////////////////////////////////////////////////////////
61 ///////////////////////////////////////////////////////////////////
63 // CLASS NAME : RepoManagerOptions
65 ///////////////////////////////////////////////////////////////////
67 RepoManagerOptions::RepoManagerOptions()
69 repoCachePath = ZConfig::instance().repoCachePath();
70 repoRawCachePath = ZConfig::instance().repoMetadataPath();
71 repoPackagesCachePath = ZConfig::instance().repoPackagesPath();
72 knownReposPath = ZConfig::instance().knownReposPath();
73 probe = ZConfig::instance().repo_add_probe();
76 ////////////////////////////////////////////////////////////////////////////
79 * \short Simple callback to collect the results
81 * Classes like RepoFileParser call the callback
82 * once per each repo in a file.
84 * Passing this functor as callback, you can collect
85 * all resuls at the end, without dealing with async
96 bool collect( const RepoInfo &repo )
98 repos.push_back(repo);
105 ////////////////////////////////////////////////////////////////////////////
108 * Reads RepoInfo's from a repo file.
110 * \param file pathname of the file to read.
112 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
114 MIL << "repo file: " << file << endl;
115 RepoCollector collector;
116 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
117 return collector.repos;
120 ////////////////////////////////////////////////////////////////////////////
122 std::list<RepoInfo> readRepoFile(const Url & repo_file)
124 // no interface to download a specific file, using workaround:
125 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
127 Pathname path(url.getPathName());
128 url.setPathName ("/");
129 MediaSetAccess access(url);
130 Pathname local = access.provideFile(path);
132 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
134 return repositories_in_file(local);
137 ////////////////////////////////////////////////////////////////////////////
140 * \short List of RepoInfo's from a directory
142 * Goes trough every file ending with ".repo" in a directory and adds all
143 * RepoInfo's contained in that file.
145 * \param dir pathname of the directory to read.
147 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
149 MIL << "directory " << dir << endl;
150 list<RepoInfo> repos;
151 list<Pathname> entries;
152 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
153 ZYPP_THROW(Exception("failed to read directory"));
155 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
156 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
158 if (str::regex_match(it->extension(), allowedRepoExt))
160 list<RepoInfo> tmp = repositories_in_file( *it );
161 repos.insert( repos.end(), tmp.begin(), tmp.end() );
163 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
164 //MIL << "ok" << endl;
170 ////////////////////////////////////////////////////////////////////////////
172 static void assert_alias( const RepoInfo &info )
174 if (info.alias().empty())
175 ZYPP_THROW(RepoNoAliasException());
178 ////////////////////////////////////////////////////////////////////////////
180 static void assert_urls( const RepoInfo &info )
182 if (info.baseUrlsEmpty())
183 ZYPP_THROW(RepoNoUrlException());
186 ////////////////////////////////////////////////////////////////////////////
189 * \short Calculates the raw cache path for a repository
191 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
194 return opt.repoRawCachePath / info.escaped_alias();
198 * \short Calculates the packages cache path for a repository
200 static Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
203 return opt.repoPackagesCachePath / info.escaped_alias();
206 ///////////////////////////////////////////////////////////////////
208 // CLASS NAME : RepoManager::Impl
210 ///////////////////////////////////////////////////////////////////
213 * \short RepoManager implementation.
215 struct RepoManager::Impl
217 Impl( const RepoManagerOptions &opt )
228 RepoManagerOptions options;
230 map<string, RepoInfo> _repoinfos;
233 /** Offer default Impl. */
234 static shared_ptr<Impl> nullimpl()
236 static shared_ptr<Impl> _nullimpl( new Impl );
241 friend Impl * rwcowClone<Impl>( const Impl * rhs );
242 /** clone for RWCOW_pointer */
244 { return new Impl( *this ); }
247 ///////////////////////////////////////////////////////////////////
249 /** \relates RepoManager::Impl Stream output */
250 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
252 return str << "RepoManager::Impl";
255 ///////////////////////////////////////////////////////////////////
257 // CLASS NAME : RepoManager
259 ///////////////////////////////////////////////////////////////////
261 RepoManager::RepoManager( const RepoManagerOptions &opt )
262 : _pimpl( new Impl(opt) )
265 ////////////////////////////////////////////////////////////////////////////
267 RepoManager::~RepoManager()
270 ////////////////////////////////////////////////////////////////////////////
272 std::list<RepoInfo> RepoManager::knownRepositories() const
276 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
278 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
279 for ( RepoInfoList::iterator it = repos.begin();
283 // set the metadata path for the repo
284 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
285 (*it).setMetadataPath(metadata_path);
287 // set the downloaded packages path for the repo
288 Pathname packages_path = packagescache_path_for_repoinfo(_pimpl->options, (*it));
289 (*it).setPackagesPath(packages_path);
294 return std::list<RepoInfo>();
299 ////////////////////////////////////////////////////////////////////////////
301 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
303 return rawcache_path_for_repoinfo(_pimpl->options, info );
306 ////////////////////////////////////////////////////////////////////////////
308 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
310 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
311 RepoType repokind = info.type();
314 switch ( repokind.toEnum() )
316 case RepoType::NONE_e:
317 // unknown, probe the local metadata
318 repokind = probe(rawpath.asUrl());
324 switch ( repokind.toEnum() )
326 case RepoType::RPMMD_e :
328 status = RepoStatus( rawpath + "/repodata/repomd.xml");
332 case RepoType::YAST2_e :
334 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
338 case RepoType::RPMPLAINDIR_e :
340 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
341 status = RepoStatus( rawpath + "/cookie");
345 case RepoType::NONE_e :
346 // Return default RepoStatus in case of RepoType::NONE
347 // indicating it should be created?
348 // ZYPP_THROW(RepoUnknownTypeException());
354 void RepoManager::touchIndexFile(const RepoInfo & info)
356 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
358 RepoType repokind = info.type();
359 if ( repokind.toEnum() == RepoType::NONE_e )
360 // unknown, probe the local metadata
361 repokind = probe(rawpath.asUrl());
362 // if still unknown, just return
363 if (repokind == RepoType::NONE_e)
367 switch ( repokind.toEnum() )
369 case RepoType::RPMMD_e :
370 p = Pathname(rawpath + "/repodata/repomd.xml");
373 case RepoType::YAST2_e :
374 p = Pathname(rawpath + "/content");
377 case RepoType::RPMPLAINDIR_e :
378 p = Pathname(rawpath + "/cookie");
381 case RepoType::NONE_e :
386 // touch the file, ignore error (they are logged anyway)
387 filesystem::touch(p);
390 RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata(
391 const RepoInfo &info,
393 RawMetadataRefreshPolicy policy )
397 RepoStatus oldstatus;
398 RepoStatus newstatus;
402 MIL << "Going to try to check whether refresh is needed for " << url << endl;
404 repo::RepoType repokind = info.type();
406 // if the type is unknown, try probing.
407 switch ( repokind.toEnum() )
409 case RepoType::NONE_e:
411 repokind = probe(url);
417 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
418 filesystem::assert_dir(rawpath);
419 oldstatus = metadataStatus(info);
421 // now we've got the old (cached) status, we can decide repo.refresh.delay
422 if (policy != RefreshForced)
424 // difference in seconds
425 double diff = difftime(
426 (Date::ValueType)Date::now(),
427 (Date::ValueType)oldstatus.timestamp()) / 60;
429 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
430 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
431 DBG << "last refresh = " << diff << " minutes ago" << endl;
433 if (diff < ZConfig::instance().repo_refresh_delay())
435 MIL << "Repository '" << info.alias()
436 << "' has been refreshed less than repo.refresh.delay ("
437 << ZConfig::instance().repo_refresh_delay()
438 << ") minutes ago. Advising to skip refresh" << endl;
439 return REPO_CHECK_DELAYED;
443 // create temp dir as sibling of rawpath
444 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
446 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
447 ( repokind.toEnum() == RepoType::YAST2_e ) )
449 MediaSetAccess media(url);
450 shared_ptr<repo::Downloader> downloader_ptr;
452 if ( repokind.toEnum() == RepoType::RPMMD_e )
453 downloader_ptr.reset(new yum::Downloader(info.path()));
455 downloader_ptr.reset( new susetags::Downloader(info.path()));
457 RepoStatus newstatus = downloader_ptr->status(media);
458 bool refresh = false;
459 if ( oldstatus.checksum() == newstatus.checksum() )
461 MIL << "repo has not changed" << endl;
462 if ( policy == RefreshForced )
464 MIL << "refresh set to forced" << endl;
470 MIL << "repo has changed, going to refresh" << endl;
475 touchIndexFile(info);
477 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
479 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
481 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
482 bool refresh = false;
483 if ( oldstatus.checksum() == newstatus.checksum() )
485 MIL << "repo has not changed" << endl;
486 if ( policy == RefreshForced )
488 MIL << "refresh set to forced" << endl;
494 MIL << "repo has changed, going to refresh" << endl;
499 touchIndexFile(info);
501 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
505 ZYPP_THROW(RepoUnknownTypeException());
508 catch ( const Exception &e )
511 ERR << "refresh check failed for " << url << endl;
515 return REFRESH_NEEDED; // default
518 void RepoManager::refreshMetadata( const RepoInfo &info,
519 RawMetadataRefreshPolicy policy,
520 const ProgressData::ReceiverFnc & progress )
525 // we will throw this later if no URL checks out fine
526 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
528 // try urls one by one
529 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
535 // check whether to refresh metadata
536 // if the check fails for this url, it throws, so another url will be checked
537 if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
540 MIL << "Going to refresh metadata from " << url << endl;
542 repo::RepoType repokind = info.type();
544 // if the type is unknown, try probing.
545 switch ( repokind.toEnum() )
547 case RepoType::NONE_e:
549 repokind = probe(*it);
551 if (repokind.toEnum() != RepoType::NONE_e)
553 //save probed type only for repos in system
554 std::list<RepoInfo> repos = knownRepositories();
555 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
556 it != repos.end(); ++it )
558 if ( info.alias() == (*it).alias() )
560 RepoInfo modifiedrepo = info;
561 modifiedrepo.setType(repokind);
562 modifyRepository(info.alias(),modifiedrepo);
571 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
572 filesystem::assert_dir(rawpath);
574 // create temp dir as sibling of rawpath
575 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
577 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
578 ( repokind.toEnum() == RepoType::YAST2_e ) )
580 MediaSetAccess media(url);
581 shared_ptr<repo::Downloader> downloader_ptr;
583 if ( repokind.toEnum() == RepoType::RPMMD_e )
584 downloader_ptr.reset(new yum::Downloader(info.path()));
586 downloader_ptr.reset( new susetags::Downloader(info.path()));
589 * Given a downloader, sets the other repos raw metadata
590 * path as cache paths for the fetcher, so if another
591 * repo has the same file, it will not download it
592 * but copy it from the other repository
594 std::list<RepoInfo> repos = knownRepositories();
595 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
599 Pathname cachepath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
600 if ( PathInfo(cachepath).isExist() )
601 downloader_ptr->addCachePath(cachepath);
604 downloader_ptr->download( media, tmpdir.path());
606 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
608 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
610 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
612 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
615 file << newstatus.checksum() << endl;
621 ZYPP_THROW(RepoUnknownTypeException());
624 // ok we have the metadata, now exchange
627 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
628 filesystem::rename( rawpath, oldmetadata.path() );
629 // move the just downloaded there
630 filesystem::rename( tmpdir.path(), rawpath );
635 catch ( const Exception &e )
638 ERR << "Trying another url..." << endl;
640 // remember the exception caught for the *first URL*
641 // if all other URLs fail, the rexception will be thrown with the
642 // cause of the problem of the first URL remembered
643 if (it == info.baseUrlsBegin())
644 rexception.remember(e);
647 ERR << "No more urls..." << endl;
648 ZYPP_THROW(rexception);
651 ////////////////////////////////////////////////////////////////////////////
653 void RepoManager::cleanMetadata( const RepoInfo &info,
654 const ProgressData::ReceiverFnc & progressfnc )
656 ProgressData progress(100);
657 progress.sendTo(progressfnc);
659 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
663 void RepoManager::cleanPackages( const RepoInfo &info,
664 const ProgressData::ReceiverFnc & progressfnc )
666 ProgressData progress(100);
667 progress.sendTo(progressfnc);
669 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
673 void RepoManager::buildCache( const RepoInfo &info,
674 CacheBuildPolicy policy,
675 const ProgressData::ReceiverFnc & progressrcv )
678 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
680 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
681 Pathname solvfile = base.extend(".solv");
684 RepoStatus raw_metadata_status = metadataStatus(info);
685 if ( raw_metadata_status.empty() )
687 /* if there is no cache at this point, we refresh the raw
688 in case this is the first time - if it's !autorefresh,
689 we may still refresh */
690 refreshMetadata(info, RefreshIfNeeded, progressrcv );
691 raw_metadata_status = metadataStatus(info);
694 bool needs_cleaning = false;
695 if ( isCached( info ) )
697 MIL << info.alias() << " is already cached." << endl;
698 //data::RecordId id = store.lookupRepository(info.alias());
699 RepoStatus cache_status = cacheStatus(info);
701 if ( cache_status.checksum() == raw_metadata_status.checksum() )
703 MIL << info.alias() << " cache is up to date with metadata." << endl;
704 if ( policy == BuildIfNeeded ) {
708 MIL << info.alias() << " cache rebuild is forced" << endl;
712 needs_cleaning = true;
715 ProgressData progress(100);
716 callback::SendReport<ProgressReport> report;
717 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
718 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
726 MIL << info.alias() << " building cache..." << endl;
728 repo::RepoType repokind = info.type();
730 // if the type is unknown, try probing.
731 switch ( repokind.toEnum() )
733 case RepoType::NONE_e:
734 // unknown, probe the local metadata
735 repokind = probe(rawpath.asUrl());
741 MIL << "repo type is " << repokind << endl;
743 switch ( repokind.toEnum() )
745 case RepoType::RPMMD_e :
746 case RepoType::YAST2_e :
747 case RepoType::RPMPLAINDIR_e :
749 // Take care we unlink the solvfile on exception
750 ManagedFile guard( solvfile, filesystem::unlink );
753 if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
755 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", info.baseUrlsBegin()->getPathName().c_str(), solvfile.c_str() );
757 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() );
759 MIL << "Executing: " << cmd.str() << endl;
760 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
763 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
764 WAR << " " << output;
765 cmd << " " << output;
768 int ret = prog.close();
771 RepoException ex(str::form("Failed to cache repo (%d).", ret));
772 ex.remember( cmd.str() );
777 guard.resetDispose();
781 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
785 switch ( repokind.toEnum() )
787 case RepoType::RPMMD_e :
790 CombinedProgressData subprogrcv( progress, 100);
791 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
792 parser.parse(rawpath);
796 case RepoType::YAST2_e :
799 CombinedProgressData subprogrcv( progress, 100);
800 parser::susetags::RepoParser parser(id, store, subprogrcv);
801 parser.parse(rawpath);
807 ZYPP_THROW(RepoUnknownTypeException());
810 // update timestamp and checksum
811 //store.updateRepositoryStatus(id, raw_metadata_status);
812 setCacheStatus(info.escaped_alias(), raw_metadata_status);
813 MIL << "Commit cache.." << endl;
818 ////////////////////////////////////////////////////////////////////////////
820 repo::RepoType RepoManager::probe( const Url &url ) const
822 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
824 // Handle non existing local directory in advance, as
825 // MediaSetAccess does not support it.
826 return repo::RepoType::NONE;
831 MediaSetAccess access(url);
832 if ( access.doesFileExist("/repodata/repomd.xml") )
833 return repo::RepoType::RPMMD;
834 if ( access.doesFileExist("/content") )
835 return repo::RepoType::YAST2;
837 // if it is a local url of type dir
838 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
840 Pathname path = Pathname(url.getPathName());
841 if ( PathInfo(path).isDir() )
843 // allow empty dirs for now
844 return repo::RepoType::RPMPLAINDIR;
848 catch ( const media::MediaException &e )
851 RepoException enew("Error trying to read from " + url.asString());
855 catch ( const Exception &e )
858 Exception enew("Unknown error reading from " + url.asString());
863 return repo::RepoType::NONE;
866 ////////////////////////////////////////////////////////////////////////////
868 void RepoManager::cleanCache( const RepoInfo &info,
869 const ProgressData::ReceiverFnc & progressrcv )
871 ProgressData progress(100);
872 progress.sendTo(progressrcv);
875 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".solv"));
877 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".cookie"));
882 void RepoManager::cleanTargetCache(const ProgressData::ReceiverFnc & progressrcv)
884 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".solv"));
885 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".cookie"));
888 ////////////////////////////////////////////////////////////////////////////
890 bool RepoManager::isCached( const RepoInfo &info ) const
892 Pathname name = _pimpl->options.repoCachePath;
893 return PathInfo(name + Pathname(info.escaped_alias()).extend(".solv")).isExist();
896 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
899 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
900 Pathname cookiefile = base.extend(".cookie");
902 return RepoStatus::fromCookieFile(cookiefile);
905 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
907 Pathname base = _pimpl->options.repoCachePath + alias;
908 Pathname cookiefile = base.extend(".cookie");
910 status.saveToCookieFile(cookiefile);
913 void RepoManager::loadFromCache( const RepoInfo & info,
914 const ProgressData::ReceiverFnc & progressrcv )
917 string alias = info.escaped_alias();
918 Pathname solvfile = (_pimpl->options.repoCachePath / alias).extend(".solv");
920 if ( ! PathInfo(solvfile).isExist() )
921 ZYPP_THROW(RepoNotCachedException());
925 sat::Pool::instance().addRepoSolv( solvfile, info );
927 catch ( const Exception & exp )
930 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
931 cleanCache( info, progressrcv );
932 buildCache( info, BuildIfNeeded, progressrcv );
934 sat::Pool::instance().addRepoSolv( solvfile, info );
938 ////////////////////////////////////////////////////////////////////////////
941 * Generate a non existing filename in a directory, using a base
942 * name. For example if a directory contains 3 files
948 * If you try to generate a unique filename for this directory,
949 * based on "ruu" you will get "ruu", but if you use the base
950 * "foo" you will get "foo_1"
952 * \param dir Directory where the file needs to be unique
953 * \param basefilename string to base the filename on.
955 static Pathname generate_non_existing_name( const Pathname &dir,
956 const std::string &basefilename )
958 string final_filename = basefilename;
960 while ( PathInfo(dir + final_filename).isExist() )
962 final_filename = basefilename + "_" + str::numstring(counter);
965 return dir + Pathname(final_filename);
968 ////////////////////////////////////////////////////////////////////////////
971 * \short Generate a related filename from a repo info
973 * From a repo info, it will try to use the alias as a filename
974 * escaping it if necessary. Other fallbacks can be added to
975 * this function in case there is no way to use the alias
977 static std::string generate_filename( const RepoInfo &info )
981 std::string filename = info.alias();
982 // replace slashes with underscores
983 size_t pos = filename.find(fnd);
984 while(pos!=string::npos)
986 filename.replace(pos,fnd.length(),rep);
987 pos = filename.find(fnd,pos+rep.length());
989 filename = Pathname(filename).extend(".repo").asString();
990 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
995 ////////////////////////////////////////////////////////////////////////////
997 void RepoManager::addRepository( const RepoInfo &info,
998 const ProgressData::ReceiverFnc & progressrcv )
1002 ProgressData progress(100);
1003 callback::SendReport<ProgressReport> report;
1004 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1005 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1008 std::list<RepoInfo> repos = knownRepositories();
1009 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1013 if ( info.alias() == (*it).alias() )
1014 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
1017 RepoInfo tosave = info;
1019 // check the first url for now
1020 if ( _pimpl->options.probe )
1022 DBG << "unknown repository type, probing" << endl;
1024 RepoType probedtype;
1025 probedtype = probe(*tosave.baseUrlsBegin());
1026 if ( tosave.baseUrlsSize() > 0 )
1028 if ( probedtype == RepoType::NONE )
1029 ZYPP_THROW(RepoUnknownTypeException());
1031 tosave.setType(probedtype);
1037 // assert the directory exists
1038 filesystem::assert_dir(_pimpl->options.knownReposPath);
1040 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1041 generate_filename(tosave));
1042 // now we have a filename that does not exists
1043 MIL << "Saving repo in " << repofile << endl;
1045 std::ofstream file(repofile.c_str());
1047 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1050 tosave.dumpRepoOn(file);
1052 MIL << "done" << endl;
1055 void RepoManager::addRepositories( const Url &url,
1056 const ProgressData::ReceiverFnc & progressrcv )
1058 std::list<RepoInfo> knownrepos = knownRepositories();
1059 std::list<RepoInfo> repos = readRepoFile(url);
1060 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1064 // look if the alias is in the known repos.
1065 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1066 kit != knownrepos.end();
1069 if ( (*it).alias() == (*kit).alias() )
1071 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1072 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1077 string filename = Pathname(url.getPathName()).basename();
1079 if ( filename == Pathname() )
1080 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1082 // assert the directory exists
1083 filesystem::assert_dir(_pimpl->options.knownReposPath);
1085 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1086 // now we have a filename that does not exists
1087 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1089 std::ofstream file(repofile.c_str());
1091 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1094 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1098 MIL << "Saving " << (*it).alias() << endl;
1099 (*it).dumpRepoOn(file);
1101 MIL << "done" << endl;
1104 ////////////////////////////////////////////////////////////////////////////
1106 void RepoManager::removeRepository( const RepoInfo & info,
1107 const ProgressData::ReceiverFnc & progressrcv)
1109 ProgressData progress;
1110 callback::SendReport<ProgressReport> report;
1111 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1112 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1114 MIL << "Going to delete repo " << info.alias() << endl;
1116 std::list<RepoInfo> repos = knownRepositories();
1117 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1121 // they can be the same only if the provided is empty, that means
1122 // the provided repo has no alias
1124 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1127 // TODO match by url
1129 // we have a matcing repository, now we need to know
1130 // where it does come from.
1131 RepoInfo todelete = *it;
1132 if (todelete.filepath().empty())
1134 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1138 // figure how many repos are there in the file:
1139 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1140 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1142 // easy, only this one, just delete the file
1143 if ( filesystem::unlink(todelete.filepath()) != 0 )
1145 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1147 MIL << todelete.alias() << " sucessfully deleted." << endl;
1151 // there are more repos in the same file
1152 // write them back except the deleted one.
1154 //std::ofstream file(tmp.path().c_str());
1156 // assert the directory exists
1157 filesystem::assert_dir(todelete.filepath().dirname());
1159 std::ofstream file(todelete.filepath().c_str());
1161 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1162 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1164 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1165 fit != filerepos.end();
1168 if ( (*fit).alias() != todelete.alias() )
1169 (*fit).dumpRepoOn(file);
1173 CombinedProgressData subprogrcv(progress, 70);
1174 CombinedProgressData cleansubprogrcv(progress, 30);
1175 // now delete it from cache
1176 if ( isCached(todelete) )
1177 cleanCache( todelete, subprogrcv);
1178 // now delete metadata (#301037)
1179 cleanMetadata( todelete, cleansubprogrcv);
1180 MIL << todelete.alias() << " sucessfully deleted." << endl;
1182 } // else filepath is empty
1185 // should not be reached on a sucess workflow
1186 ZYPP_THROW(RepoNotFoundException(info));
1189 ////////////////////////////////////////////////////////////////////////////
1191 void RepoManager::modifyRepository( const std::string &alias,
1192 const RepoInfo & newinfo,
1193 const ProgressData::ReceiverFnc & progressrcv )
1195 RepoInfo toedit = getRepositoryInfo(alias);
1197 // check if the new alias already exists when renaming the repo
1198 if (alias != newinfo.alias())
1200 std::list<RepoInfo> repos = knownRepositories();
1201 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1205 if ( newinfo.alias() == (*it).alias() )
1206 ZYPP_THROW(RepoAlreadyExistsException(newinfo.alias()));
1210 if (toedit.filepath().empty())
1212 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1216 // figure how many repos are there in the file:
1217 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1219 // there are more repos in the same file
1220 // write them back except the deleted one.
1222 //std::ofstream file(tmp.path().c_str());
1224 // assert the directory exists
1225 filesystem::assert_dir(toedit.filepath().dirname());
1227 std::ofstream file(toedit.filepath().c_str());
1229 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1230 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1232 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1233 fit != filerepos.end();
1236 // if the alias is different, dump the original
1237 // if it is the same, dump the provided one
1238 if ( (*fit).alias() != toedit.alias() )
1239 (*fit).dumpRepoOn(file);
1241 newinfo.dumpRepoOn(file);
1246 ////////////////////////////////////////////////////////////////////////////
1248 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1249 const ProgressData::ReceiverFnc & progressrcv )
1251 std::list<RepoInfo> repos = knownRepositories();
1252 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1256 if ( (*it).alias() == alias )
1260 info.setAlias(info.alias());
1261 ZYPP_THROW(RepoNotFoundException(info));
1264 ////////////////////////////////////////////////////////////////////////////
1266 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1267 const url::ViewOption & urlview,
1268 const ProgressData::ReceiverFnc & progressrcv )
1270 std::list<RepoInfo> repos = knownRepositories();
1271 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1275 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1276 urlit != (*it).baseUrlsEnd();
1279 if ((*urlit).asString(urlview) == url.asString(urlview))
1284 info.setAlias(info.alias());
1285 info.setBaseUrl(url);
1286 ZYPP_THROW(RepoNotFoundException(info));
1289 ////////////////////////////////////////////////////////////////////////////
1291 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1293 return str << *obj._pimpl;
1296 /////////////////////////////////////////////////////////////////
1298 ///////////////////////////////////////////////////////////////////