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 filesystem::assert_dir(_pimpl->options.repoCachePath);
681 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
682 Pathname solvfile = base.extend(".solv");
685 RepoStatus raw_metadata_status = metadataStatus(info);
686 if ( raw_metadata_status.empty() )
688 /* if there is no cache at this point, we refresh the raw
689 in case this is the first time - if it's !autorefresh,
690 we may still refresh */
691 refreshMetadata(info, RefreshIfNeeded, progressrcv );
692 raw_metadata_status = metadataStatus(info);
695 bool needs_cleaning = false;
696 if ( isCached( info ) )
698 MIL << info.alias() << " is already cached." << endl;
699 //data::RecordId id = store.lookupRepository(info.alias());
700 RepoStatus cache_status = cacheStatus(info);
702 if ( cache_status.checksum() == raw_metadata_status.checksum() )
704 MIL << info.alias() << " cache is up to date with metadata." << endl;
705 if ( policy == BuildIfNeeded ) {
709 MIL << info.alias() << " cache rebuild is forced" << endl;
713 needs_cleaning = true;
716 ProgressData progress(100);
717 callback::SendReport<ProgressReport> report;
718 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
719 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
727 MIL << info.alias() << " building cache..." << endl;
729 repo::RepoType repokind = info.type();
731 // if the type is unknown, try probing.
732 switch ( repokind.toEnum() )
734 case RepoType::NONE_e:
735 // unknown, probe the local metadata
736 repokind = probe(rawpath.asUrl());
742 MIL << "repo type is " << repokind << endl;
744 switch ( repokind.toEnum() )
746 case RepoType::RPMMD_e :
747 case RepoType::YAST2_e :
748 case RepoType::RPMPLAINDIR_e :
750 // Take care we unlink the solvfile on exception
751 ManagedFile guard( solvfile, filesystem::unlink );
754 if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
756 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", info.baseUrlsBegin()->getPathName().c_str(), solvfile.c_str() );
758 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() );
760 MIL << "Executing: " << cmd.str() << endl;
761 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
764 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
765 WAR << " " << output;
766 cmd << " " << output;
769 int ret = prog.close();
772 RepoException ex(str::form("Failed to cache repo (%d).", ret));
773 ex.remember( cmd.str() );
778 guard.resetDispose();
782 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
786 switch ( repokind.toEnum() )
788 case RepoType::RPMMD_e :
791 CombinedProgressData subprogrcv( progress, 100);
792 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
793 parser.parse(rawpath);
797 case RepoType::YAST2_e :
800 CombinedProgressData subprogrcv( progress, 100);
801 parser::susetags::RepoParser parser(id, store, subprogrcv);
802 parser.parse(rawpath);
808 ZYPP_THROW(RepoUnknownTypeException());
811 // update timestamp and checksum
812 //store.updateRepositoryStatus(id, raw_metadata_status);
813 setCacheStatus(info.escaped_alias(), raw_metadata_status);
814 MIL << "Commit cache.." << endl;
819 ////////////////////////////////////////////////////////////////////////////
821 repo::RepoType RepoManager::probe( const Url &url ) const
823 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
825 // Handle non existing local directory in advance, as
826 // MediaSetAccess does not support it.
827 return repo::RepoType::NONE;
832 MediaSetAccess access(url);
833 if ( access.doesFileExist("/repodata/repomd.xml") )
834 return repo::RepoType::RPMMD;
835 if ( access.doesFileExist("/content") )
836 return repo::RepoType::YAST2;
838 // if it is a local url of type dir
839 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
841 Pathname path = Pathname(url.getPathName());
842 if ( PathInfo(path).isDir() )
844 // allow empty dirs for now
845 return repo::RepoType::RPMPLAINDIR;
849 catch ( const media::MediaException &e )
852 RepoException enew("Error trying to read from " + url.asString());
856 catch ( const Exception &e )
859 Exception enew("Unknown error reading from " + url.asString());
864 return repo::RepoType::NONE;
867 ////////////////////////////////////////////////////////////////////////////
869 void RepoManager::cleanCache( const RepoInfo &info,
870 const ProgressData::ReceiverFnc & progressrcv )
872 ProgressData progress(100);
873 progress.sendTo(progressrcv);
876 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".solv"));
878 unlink (_pimpl->options.repoCachePath / (info.escaped_alias() + ".cookie"));
883 void RepoManager::cleanTargetCache(const ProgressData::ReceiverFnc & progressrcv)
885 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".solv"));
886 unlink (_pimpl->options.repoCachePath / (sat::Pool::systemRepoName() + ".cookie"));
889 ////////////////////////////////////////////////////////////////////////////
891 bool RepoManager::isCached( const RepoInfo &info ) const
893 Pathname name = _pimpl->options.repoCachePath;
894 return PathInfo(name + Pathname(info.escaped_alias()).extend(".solv")).isExist();
897 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
900 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
901 Pathname cookiefile = base.extend(".cookie");
903 return RepoStatus::fromCookieFile(cookiefile);
906 void RepoManager::setCacheStatus( const string &alias, const RepoStatus &status )
908 filesystem::assert_dir(_pimpl->options.repoCachePath);
909 Pathname base = _pimpl->options.repoCachePath + alias;
910 Pathname cookiefile = base.extend(".cookie");
912 status.saveToCookieFile(cookiefile);
915 void RepoManager::loadFromCache( const RepoInfo & info,
916 const ProgressData::ReceiverFnc & progressrcv )
919 string alias = info.escaped_alias();
920 Pathname solvfile = (_pimpl->options.repoCachePath / alias).extend(".solv");
922 if ( ! PathInfo(solvfile).isExist() )
923 ZYPP_THROW(RepoNotCachedException());
927 sat::Pool::instance().addRepoSolv( solvfile, info );
929 catch ( const Exception & exp )
932 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
933 cleanCache( info, progressrcv );
934 buildCache( info, BuildIfNeeded, progressrcv );
936 sat::Pool::instance().addRepoSolv( solvfile, info );
940 ////////////////////////////////////////////////////////////////////////////
943 * Generate a non existing filename in a directory, using a base
944 * name. For example if a directory contains 3 files
950 * If you try to generate a unique filename for this directory,
951 * based on "ruu" you will get "ruu", but if you use the base
952 * "foo" you will get "foo_1"
954 * \param dir Directory where the file needs to be unique
955 * \param basefilename string to base the filename on.
957 static Pathname generate_non_existing_name( const Pathname &dir,
958 const std::string &basefilename )
960 string final_filename = basefilename;
962 while ( PathInfo(dir + final_filename).isExist() )
964 final_filename = basefilename + "_" + str::numstring(counter);
967 return dir + Pathname(final_filename);
970 ////////////////////////////////////////////////////////////////////////////
973 * \short Generate a related filename from a repo info
975 * From a repo info, it will try to use the alias as a filename
976 * escaping it if necessary. Other fallbacks can be added to
977 * this function in case there is no way to use the alias
979 static std::string generate_filename( const RepoInfo &info )
983 std::string filename = info.alias();
984 // replace slashes with underscores
985 size_t pos = filename.find(fnd);
986 while(pos!=string::npos)
988 filename.replace(pos,fnd.length(),rep);
989 pos = filename.find(fnd,pos+rep.length());
991 filename = Pathname(filename).extend(".repo").asString();
992 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
997 ////////////////////////////////////////////////////////////////////////////
999 void RepoManager::addRepository( const RepoInfo &info,
1000 const ProgressData::ReceiverFnc & progressrcv )
1004 ProgressData progress(100);
1005 callback::SendReport<ProgressReport> report;
1006 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1007 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1010 std::list<RepoInfo> repos = knownRepositories();
1011 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1015 if ( info.alias() == (*it).alias() )
1016 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
1019 RepoInfo tosave = info;
1021 // check the first url for now
1022 if ( _pimpl->options.probe )
1024 DBG << "unknown repository type, probing" << endl;
1026 RepoType probedtype;
1027 probedtype = probe(*tosave.baseUrlsBegin());
1028 if ( tosave.baseUrlsSize() > 0 )
1030 if ( probedtype == RepoType::NONE )
1031 ZYPP_THROW(RepoUnknownTypeException());
1033 tosave.setType(probedtype);
1039 // assert the directory exists
1040 filesystem::assert_dir(_pimpl->options.knownReposPath);
1042 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1043 generate_filename(tosave));
1044 // now we have a filename that does not exists
1045 MIL << "Saving repo in " << repofile << endl;
1047 std::ofstream file(repofile.c_str());
1049 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1052 tosave.dumpRepoOn(file);
1054 MIL << "done" << endl;
1057 void RepoManager::addRepositories( const Url &url,
1058 const ProgressData::ReceiverFnc & progressrcv )
1060 std::list<RepoInfo> knownrepos = knownRepositories();
1061 std::list<RepoInfo> repos = readRepoFile(url);
1062 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1066 // look if the alias is in the known repos.
1067 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1068 kit != knownrepos.end();
1071 if ( (*it).alias() == (*kit).alias() )
1073 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1074 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1079 string filename = Pathname(url.getPathName()).basename();
1081 if ( filename == Pathname() )
1082 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1084 // assert the directory exists
1085 filesystem::assert_dir(_pimpl->options.knownReposPath);
1087 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1088 // now we have a filename that does not exists
1089 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1091 std::ofstream file(repofile.c_str());
1093 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1096 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1100 MIL << "Saving " << (*it).alias() << endl;
1101 (*it).dumpRepoOn(file);
1103 MIL << "done" << endl;
1106 ////////////////////////////////////////////////////////////////////////////
1108 void RepoManager::removeRepository( const RepoInfo & info,
1109 const ProgressData::ReceiverFnc & progressrcv)
1111 ProgressData progress;
1112 callback::SendReport<ProgressReport> report;
1113 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1114 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1116 MIL << "Going to delete repo " << info.alias() << endl;
1118 std::list<RepoInfo> repos = knownRepositories();
1119 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1123 // they can be the same only if the provided is empty, that means
1124 // the provided repo has no alias
1126 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1129 // TODO match by url
1131 // we have a matcing repository, now we need to know
1132 // where it does come from.
1133 RepoInfo todelete = *it;
1134 if (todelete.filepath().empty())
1136 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1140 // figure how many repos are there in the file:
1141 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1142 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1144 // easy, only this one, just delete the file
1145 if ( filesystem::unlink(todelete.filepath()) != 0 )
1147 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1149 MIL << todelete.alias() << " sucessfully deleted." << endl;
1153 // there are more repos in the same file
1154 // write them back except the deleted one.
1156 //std::ofstream file(tmp.path().c_str());
1158 // assert the directory exists
1159 filesystem::assert_dir(todelete.filepath().dirname());
1161 std::ofstream file(todelete.filepath().c_str());
1163 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1164 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1166 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1167 fit != filerepos.end();
1170 if ( (*fit).alias() != todelete.alias() )
1171 (*fit).dumpRepoOn(file);
1175 CombinedProgressData subprogrcv(progress, 70);
1176 CombinedProgressData cleansubprogrcv(progress, 30);
1177 // now delete it from cache
1178 if ( isCached(todelete) )
1179 cleanCache( todelete, subprogrcv);
1180 // now delete metadata (#301037)
1181 cleanMetadata( todelete, cleansubprogrcv);
1182 MIL << todelete.alias() << " sucessfully deleted." << endl;
1184 } // else filepath is empty
1187 // should not be reached on a sucess workflow
1188 ZYPP_THROW(RepoNotFoundException(info));
1191 ////////////////////////////////////////////////////////////////////////////
1193 void RepoManager::modifyRepository( const std::string &alias,
1194 const RepoInfo & newinfo,
1195 const ProgressData::ReceiverFnc & progressrcv )
1197 RepoInfo toedit = getRepositoryInfo(alias);
1199 // check if the new alias already exists when renaming the repo
1200 if (alias != newinfo.alias())
1202 std::list<RepoInfo> repos = knownRepositories();
1203 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1207 if ( newinfo.alias() == (*it).alias() )
1208 ZYPP_THROW(RepoAlreadyExistsException(newinfo.alias()));
1212 if (toedit.filepath().empty())
1214 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1218 // figure how many repos are there in the file:
1219 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1221 // there are more repos in the same file
1222 // write them back except the deleted one.
1224 //std::ofstream file(tmp.path().c_str());
1226 // assert the directory exists
1227 filesystem::assert_dir(toedit.filepath().dirname());
1229 std::ofstream file(toedit.filepath().c_str());
1231 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1232 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1234 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1235 fit != filerepos.end();
1238 // if the alias is different, dump the original
1239 // if it is the same, dump the provided one
1240 if ( (*fit).alias() != toedit.alias() )
1241 (*fit).dumpRepoOn(file);
1243 newinfo.dumpRepoOn(file);
1248 ////////////////////////////////////////////////////////////////////////////
1250 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1251 const ProgressData::ReceiverFnc & progressrcv )
1253 std::list<RepoInfo> repos = knownRepositories();
1254 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1258 if ( (*it).alias() == alias )
1262 info.setAlias(info.alias());
1263 ZYPP_THROW(RepoNotFoundException(info));
1266 ////////////////////////////////////////////////////////////////////////////
1268 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1269 const url::ViewOption & urlview,
1270 const ProgressData::ReceiverFnc & progressrcv )
1272 std::list<RepoInfo> repos = knownRepositories();
1273 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1277 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1278 urlit != (*it).baseUrlsEnd();
1281 if ((*urlit).asString(urlview) == url.asString(urlview))
1286 info.setAlias(info.alias());
1287 info.setBaseUrl(url);
1288 ZYPP_THROW(RepoNotFoundException(info));
1291 ////////////////////////////////////////////////////////////////////////////
1293 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1295 return str << *obj._pimpl;
1298 /////////////////////////////////////////////////////////////////
1300 ///////////////////////////////////////////////////////////////////