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
98 bool collect( const RepoInfo &repo )
100 //MIL << "here in collector: " << repo.alias() << endl;
101 repos.push_back(repo);
102 //MIL << "added: " << repo.alias() << endl;
109 ////////////////////////////////////////////////////////////////////////////
112 * Reads RepoInfo's from a repo file.
114 * \param file pathname of the file to read.
116 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
118 MIL << "repo file: " << file << endl;
119 RepoCollector collector;
120 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
121 return collector.repos;
124 ////////////////////////////////////////////////////////////////////////////
126 std::list<RepoInfo> readRepoFile(const Url & repo_file)
128 // no interface to download a specific file, using workaround:
129 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
131 Pathname path(url.getPathName());
132 url.setPathName ("/");
133 MediaSetAccess access(url);
134 Pathname local = access.provideFile(path);
136 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
138 return repositories_in_file(local);
141 ////////////////////////////////////////////////////////////////////////////
144 * \short List of RepoInfo's from a directory
146 * Goes trough every file ending with ".repo" in a directory and adds all
147 * RepoInfo's contained in that file.
149 * \param dir pathname of the directory to read.
151 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
153 MIL << "directory " << dir << endl;
154 list<RepoInfo> repos;
155 list<Pathname> entries;
156 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
157 ZYPP_THROW(Exception("failed to read directory"));
159 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
160 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
162 if (str::regex_match(it->extension(), allowedRepoExt))
164 list<RepoInfo> tmp = repositories_in_file( *it );
165 repos.insert( repos.end(), tmp.begin(), tmp.end() );
167 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
168 //MIL << "ok" << endl;
174 ////////////////////////////////////////////////////////////////////////////
176 static void assert_alias( const RepoInfo &info )
178 if (info.alias().empty())
179 ZYPP_THROW(RepoNoAliasException());
182 ////////////////////////////////////////////////////////////////////////////
184 static void assert_urls( const RepoInfo &info )
186 if (info.baseUrlsEmpty())
187 ZYPP_THROW(RepoNoUrlException());
190 ////////////////////////////////////////////////////////////////////////////
193 * \short Calculates the raw cache path for a repository
195 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
198 return opt.repoRawCachePath + info.alias();
202 * \short Calculates the packages cache path for a repository
204 static Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
207 return opt.repoPackagesCachePath + info.alias();
210 ///////////////////////////////////////////////////////////////////
212 // CLASS NAME : RepoManager::Impl
214 ///////////////////////////////////////////////////////////////////
217 * \short RepoManager implementation.
219 struct RepoManager::Impl
221 Impl( const RepoManagerOptions &opt )
232 RepoManagerOptions options;
234 map<string, RepoInfo> _repoinfos;
237 /** Offer default Impl. */
238 static shared_ptr<Impl> nullimpl()
240 static shared_ptr<Impl> _nullimpl( new Impl );
245 friend Impl * rwcowClone<Impl>( const Impl * rhs );
246 /** clone for RWCOW_pointer */
248 { return new Impl( *this ); }
251 ///////////////////////////////////////////////////////////////////
253 /** \relates RepoManager::Impl Stream output */
254 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
256 return str << "RepoManager::Impl";
259 ///////////////////////////////////////////////////////////////////
261 // CLASS NAME : RepoManager
263 ///////////////////////////////////////////////////////////////////
265 RepoManager::RepoManager( const RepoManagerOptions &opt )
266 : _pimpl( new Impl(opt) )
269 ////////////////////////////////////////////////////////////////////////////
271 RepoManager::~RepoManager()
274 ////////////////////////////////////////////////////////////////////////////
276 std::list<RepoInfo> RepoManager::knownRepositories() const
280 if ( PathInfo(_pimpl->options.knownReposPath).isExist() )
282 RepoInfoList repos = repositories_in_dir(_pimpl->options.knownReposPath);
283 for ( RepoInfoList::iterator it = repos.begin();
287 // set the metadata path for the repo
288 Pathname metadata_path = rawcache_path_for_repoinfo(_pimpl->options, (*it));
289 (*it).setMetadataPath(metadata_path);
291 // set the downloaded packages path for the repo
292 Pathname packages_path = packagescache_path_for_repoinfo(_pimpl->options, (*it));
293 (*it).setPackagesPath(packages_path);
298 return std::list<RepoInfo>();
303 ////////////////////////////////////////////////////////////////////////////
305 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
307 return rawcache_path_for_repoinfo(_pimpl->options, info );
310 ////////////////////////////////////////////////////////////////////////////
312 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
314 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
315 RepoType repokind = info.type();
318 switch ( repokind.toEnum() )
320 case RepoType::NONE_e:
321 // unknown, probe the local metadata
322 repokind = probe(rawpath.asUrl());
328 switch ( repokind.toEnum() )
330 case RepoType::RPMMD_e :
332 status = RepoStatus( rawpath + "/repodata/repomd.xml");
336 case RepoType::YAST2_e :
338 // the order of RepoStatus && RepoStatus matters! (#304310)
339 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
343 case RepoType::RPMPLAINDIR_e :
345 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
346 status = RepoStatus( rawpath + "/cookie");
350 case RepoType::NONE_e :
351 // Return default RepoStatus in case of RepoType::NONE
352 // indicating it should be created?
353 // ZYPP_THROW(RepoUnknownTypeException());
359 void RepoManager::touchIndexFile(const RepoInfo & info)
361 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
363 RepoType repokind = info.type();
364 if ( repokind.toEnum() == RepoType::NONE_e )
365 // unknown, probe the local metadata
366 repokind = probe(rawpath.asUrl());
367 // if still unknown, just return
368 if (repokind == RepoType::NONE_e)
372 switch ( repokind.toEnum() )
374 case RepoType::RPMMD_e :
375 p = Pathname(rawpath + "/repodata/repomd.xml");
378 case RepoType::YAST2_e :
379 p = Pathname(rawpath + "/content");
382 case RepoType::RPMPLAINDIR_e :
383 p = Pathname(rawpath + "/cookie");
386 case RepoType::NONE_e :
391 // touch the file, ignore error (they are logged anyway)
392 filesystem::touch(p);
395 bool RepoManager::checkIfToRefreshMetadata( const RepoInfo &info,
397 RawMetadataRefreshPolicy policy )
401 RepoStatus oldstatus;
402 RepoStatus newstatus;
406 MIL << "Going to try to check whether refresh is needed for " << url << endl;
408 repo::RepoType repokind = info.type();
410 // if the type is unknown, try probing.
411 switch ( repokind.toEnum() )
413 case RepoType::NONE_e:
415 repokind = probe(url);
421 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
422 filesystem::assert_dir(rawpath);
423 oldstatus = metadataStatus(info);
425 // now we've got the old (cached) status, we can decide repo.refresh.delay
426 if (policy != RefreshForced)
428 // difference in seconds
429 double diff = difftime(
430 (Date::ValueType)Date::now(),
431 (Date::ValueType)oldstatus.timestamp()) / 60;
433 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
434 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
435 DBG << "last refresh = " << diff << " minutes ago" << endl;
437 if (diff < ZConfig::instance().repo_refresh_delay())
439 MIL << "Repository '" << info.alias()
440 << "' has been refreshed less than repo.refresh.delay ("
441 << ZConfig::instance().repo_refresh_delay()
442 << ") minutes ago. Advising to skip refresh" << endl;
447 // create temp dir as sibling of rawpath
448 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
450 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
451 ( repokind.toEnum() == RepoType::YAST2_e ) )
453 MediaSetAccess media(url);
454 shared_ptr<repo::Downloader> downloader_ptr;
456 if ( repokind.toEnum() == RepoType::RPMMD_e )
457 downloader_ptr.reset(new yum::Downloader(info.path()));
459 downloader_ptr.reset( new susetags::Downloader(info.path()));
461 RepoStatus newstatus = downloader_ptr->status(media);
462 bool refresh = false;
463 if ( oldstatus.checksum() == newstatus.checksum() )
465 MIL << "repo has not changed" << endl;
466 if ( policy == RefreshForced )
468 MIL << "refresh set to forced" << endl;
474 MIL << "repo has changed, going to refresh" << endl;
479 touchIndexFile(info);
484 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
486 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
487 bool refresh = false;
488 if ( oldstatus.checksum() == newstatus.checksum() )
490 MIL << "repo has not changed" << endl;
491 if ( policy == RefreshForced )
493 MIL << "refresh set to forced" << endl;
499 MIL << "repo has changed, going to refresh" << endl;
504 touchIndexFile(info);
511 ZYPP_THROW(RepoUnknownTypeException());
514 catch ( const Exception &e )
517 ERR << "refresh check failed for " << url << endl;
521 return true; // default
524 void RepoManager::refreshMetadata( const RepoInfo &info,
525 RawMetadataRefreshPolicy policy,
526 const ProgressData::ReceiverFnc & progress )
531 // we will throw this later if no URL checks out fine
532 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
534 // try urls one by one
535 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
541 // check whether to refresh metadata
542 // if the check fails for this url, it throws, so another url will be checked
543 if (!checkIfToRefreshMetadata(info, url, policy))
546 MIL << "Going to refresh metadata from " << url << endl;
548 repo::RepoType repokind = info.type();
550 // if the type is unknown, try probing.
551 switch ( repokind.toEnum() )
553 case RepoType::NONE_e:
555 repokind = probe(*it);
561 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
562 filesystem::assert_dir(rawpath);
564 // create temp dir as sibling of rawpath
565 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
567 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
568 ( repokind.toEnum() == RepoType::YAST2_e ) )
570 MediaSetAccess media(url);
571 shared_ptr<repo::Downloader> downloader_ptr;
573 if ( repokind.toEnum() == RepoType::RPMMD_e )
574 downloader_ptr.reset(new yum::Downloader(info.path()));
576 downloader_ptr.reset( new susetags::Downloader(info.path()));
579 * Given a downloader, sets the other repos raw metadata
580 * path as cache paths for the fetcher, so if another
581 * repo has the same file, it will not download it
582 * but copy it from the other repository
584 std::list<RepoInfo> repos = knownRepositories();
585 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
589 downloader_ptr->addCachePath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
592 downloader_ptr->download( media, tmpdir.path());
595 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
597 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
599 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
601 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
604 file << newstatus.checksum() << endl;
611 ZYPP_THROW(RepoUnknownTypeException());
614 // ok we have the metadata, now exchange
617 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
618 filesystem::rename( rawpath, oldmetadata.path() );
619 // move the just downloaded there
620 filesystem::rename( tmpdir.path(), rawpath );
625 catch ( const Exception &e )
628 ERR << "Trying another url..." << endl;
630 // remember the exception caught for the *first URL*
631 // if all other URLs fail, the rexception will be thrown with the
632 // cause of the problem of the first URL remembered
633 if (it == info.baseUrlsBegin())
634 rexception.remember(e);
637 ERR << "No more urls..." << endl;
638 ZYPP_THROW(rexception);
641 ////////////////////////////////////////////////////////////////////////////
643 void RepoManager::cleanMetadata( const RepoInfo &info,
644 const ProgressData::ReceiverFnc & progressfnc )
646 ProgressData progress(100);
647 progress.sendTo(progressfnc);
649 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
653 void RepoManager::cleanPackages( const RepoInfo &info,
654 const ProgressData::ReceiverFnc & progressfnc )
656 ProgressData progress(100);
657 progress.sendTo(progressfnc);
659 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
663 void RepoManager::buildCache( const RepoInfo &info,
664 CacheBuildPolicy policy,
665 const ProgressData::ReceiverFnc & progressrcv )
668 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
670 Pathname base = _pimpl->options.repoCachePath + info.escaped_alias();
671 Pathname solvfile = base.extend(".solv");
673 //cache::SolvStore store(_pimpl->options.repoCachePath);
675 RepoStatus raw_metadata_status = metadataStatus(info);
676 if ( raw_metadata_status.empty() )
678 /* if there is no cache at this point, we refresh the raw
679 in case this is the first time - if it's !autorefresh,
680 we may still refresh */
681 refreshMetadata(info, RefreshIfNeeded, progressrcv );
684 bool needs_cleaning = false;
685 if ( isCached( info ) )
687 MIL << info.alias() << " is already cached." << endl;
688 //data::RecordId id = store.lookupRepository(info.alias());
689 RepoStatus cache_status = cacheStatus(info);
691 if ( cache_status.checksum() == raw_metadata_status.checksum() )
693 MIL << info.alias() << " cache is up to date with metadata." << endl;
694 if ( policy == BuildIfNeeded ) {
698 MIL << info.alias() << " cache rebuild is forced" << endl;
702 needs_cleaning = true;
705 /* if there is no cache at this point, we refresh the raw
706 in case this is the first time - if it's !autorefresh,
707 we may still refresh */
708 refreshMetadata(info, RefreshIfNeeded, progressrcv );
711 ProgressData progress(100);
712 callback::SendReport<ProgressReport> report;
713 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
714 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
719 // Pathname name = _pimpl->options.repoCachePath;
720 // //data::RecordId id = store.lookupRepository(info.alias());
723 // name += os.str() + ".solv";
725 // cleanCacheInternal( store, info);
729 MIL << info.alias() << " building cache..." << endl;
730 //data::RecordId id = store.lookupOrAppendRepository(info.alias());
732 repo::RepoType repokind = info.type();
734 // if the type is unknown, try probing.
735 switch ( repokind.toEnum() )
737 case RepoType::NONE_e:
738 // unknown, probe the local metadata
739 repokind = probe(rawpath.asUrl());
745 MIL << "repo type is " << repokind << endl;
747 switch ( repokind.toEnum() )
749 case RepoType::RPMMD_e :
750 case RepoType::YAST2_e :
752 // Take care we unlink the solvfile on exception
753 ManagedFile guard( solvfile, filesystem::unlink );
756 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"", rawpath.c_str(), solvfile.c_str() );
758 MIL << "Executing: " << cmd.str() << endl;
759 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
762 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
763 WAR << " " << output;
764 cmd << " " << output;
767 int ret = prog.close();
770 RepoException ex(str::form("Failed to cache repo (%d).", ret));
771 ex.remember( cmd.str() );
776 guard.resetDispose();
780 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
784 switch ( repokind.toEnum() )
786 case RepoType::RPMMD_e :
789 CombinedProgressData subprogrcv( progress, 100);
790 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
791 parser.parse(rawpath);
795 case RepoType::YAST2_e :
798 CombinedProgressData subprogrcv( progress, 100);
799 parser::susetags::RepoParser parser(id, store, subprogrcv);
800 parser.parse(rawpath);
806 case RepoType::RPMPLAINDIR_e :
808 CombinedProgressData subprogrcv( progress, 100);
809 InputStream is(rawpath + "cookie");
811 getline( is.stream(), buffer);
813 parser::plaindir::RepoParser parser(id, store, subprogrcv);
814 parser.parse(url.getPathName());
819 ZYPP_THROW(RepoUnknownTypeException());
822 // update timestamp and checksum
823 //store.updateRepositoryStatus(id, raw_metadata_status);
824 setCacheStatus(info.escaped_alias(), raw_metadata_status);
825 MIL << "Commit cache.." << endl;
830 ////////////////////////////////////////////////////////////////////////////
832 repo::RepoType RepoManager::probe( const Url &url ) const
834 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
836 // Handle non existing local directory in advance, as
837 // MediaSetAccess does not support it.
838 return repo::RepoType::NONE;
843 MediaSetAccess access(url);
844 if ( access.doesFileExist("/repodata/repomd.xml") )
845 return repo::RepoType::RPMMD;
846 if ( access.doesFileExist("/content") )
847 return repo::RepoType::YAST2;
849 // if it is a local url of type dir
850 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
852 Pathname path = Pathname(url.getPathName());
853 if ( PathInfo(path).isDir() )
855 // allow empty dirs for now
856 return repo::RepoType::RPMPLAINDIR;
860 catch ( const media::MediaException &e )
863 RepoException enew("Error trying to read from " + url.asString());
867 catch ( const Exception &e )
870 Exception enew("Unknown error reading from " + url.asString());
875 return repo::RepoType::NONE;
878 ////////////////////////////////////////////////////////////////////////////
880 void RepoManager::cleanCache( const RepoInfo &info,
881 const ProgressData::ReceiverFnc & progressrcv )
883 Pathname name = _pimpl->options.repoCachePath;
884 name += info.escaped_alias() + ".solv";
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 sat::Pool satpool( sat::Pool::instance() );
918 string alias = info.escaped_alias();
920 Pathname solvfile = (_pimpl->options.repoCachePath + alias).extend(".solv");
922 if ( ! PathInfo(solvfile).isExist() )
923 ZYPP_THROW(RepoNotCachedException());
925 Repository repo = satpool.addRepoSolv(solvfile, info);
928 ////////////////////////////////////////////////////////////////////////////
931 * Generate a non existing filename in a directory, using a base
932 * name. For example if a directory contains 3 files
938 * If you try to generate a unique filename for this directory,
939 * based on "ruu" you will get "ruu", but if you use the base
940 * "foo" you will get "foo_1"
942 * \param dir Directory where the file needs to be unique
943 * \param basefilename string to base the filename on.
945 static Pathname generate_non_existing_name( const Pathname &dir,
946 const std::string &basefilename )
948 string final_filename = basefilename;
950 while ( PathInfo(dir + final_filename).isExist() )
952 final_filename = basefilename + "_" + str::numstring(counter);
955 return dir + Pathname(final_filename);
958 ////////////////////////////////////////////////////////////////////////////
961 * \short Generate a related filename from a repo info
963 * From a repo info, it will try to use the alias as a filename
964 * escaping it if necessary. Other fallbacks can be added to
965 * this function in case there is no way to use the alias
967 static std::string generate_filename( const RepoInfo &info )
971 std::string filename = info.alias();
972 // replace slashes with underscores
973 size_t pos = filename.find(fnd);
974 while(pos!=string::npos)
976 filename.replace(pos,fnd.length(),rep);
977 pos = filename.find(fnd,pos+rep.length());
979 filename = Pathname(filename).extend(".repo").asString();
980 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
985 ////////////////////////////////////////////////////////////////////////////
987 void RepoManager::addRepository( const RepoInfo &info,
988 const ProgressData::ReceiverFnc & progressrcv )
992 ProgressData progress(100);
993 callback::SendReport<ProgressReport> report;
994 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
995 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
998 std::list<RepoInfo> repos = knownRepositories();
999 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1003 if ( info.alias() == (*it).alias() )
1004 ZYPP_THROW(RepoAlreadyExistsException(info.alias()));
1007 RepoInfo tosave = info;
1009 // check the first url for now
1010 if ( ZConfig::instance().repo_add_probe()
1011 || ( tosave.type() == RepoType::NONE && tosave.enabled()) )
1013 DBG << "unknown repository type, probing" << endl;
1015 RepoType probedtype;
1016 probedtype = probe(*tosave.baseUrlsBegin());
1017 if ( tosave.baseUrlsSize() > 0 )
1019 if ( probedtype == RepoType::NONE )
1020 ZYPP_THROW(RepoUnknownTypeException());
1022 tosave.setType(probedtype);
1028 // assert the directory exists
1029 filesystem::assert_dir(_pimpl->options.knownReposPath);
1031 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath,
1032 generate_filename(tosave));
1033 // now we have a filename that does not exists
1034 MIL << "Saving repo in " << repofile << endl;
1036 std::ofstream file(repofile.c_str());
1038 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1041 tosave.dumpRepoOn(file);
1043 MIL << "done" << endl;
1046 void RepoManager::addRepositories( const Url &url,
1047 const ProgressData::ReceiverFnc & progressrcv )
1049 std::list<RepoInfo> knownrepos = knownRepositories();
1050 std::list<RepoInfo> repos = readRepoFile(url);
1051 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1055 // look if the alias is in the known repos.
1056 for ( std::list<RepoInfo>::const_iterator kit = knownrepos.begin();
1057 kit != knownrepos.end();
1060 if ( (*it).alias() == (*kit).alias() )
1062 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1063 ZYPP_THROW(RepoAlreadyExistsException((*it).alias()));
1068 string filename = Pathname(url.getPathName()).basename();
1070 if ( filename == Pathname() )
1071 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1073 // assert the directory exists
1074 filesystem::assert_dir(_pimpl->options.knownReposPath);
1076 Pathname repofile = generate_non_existing_name(_pimpl->options.knownReposPath, filename);
1077 // now we have a filename that does not exists
1078 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1080 std::ofstream file(repofile.c_str());
1082 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1085 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1089 MIL << "Saving " << (*it).alias() << endl;
1090 (*it).dumpRepoOn(file);
1092 MIL << "done" << endl;
1095 ////////////////////////////////////////////////////////////////////////////
1097 void RepoManager::removeRepository( const RepoInfo & info,
1098 const ProgressData::ReceiverFnc & progressrcv)
1100 ProgressData progress;
1101 callback::SendReport<ProgressReport> report;
1102 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1103 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1105 MIL << "Going to delete repo " << info.alias() << endl;
1107 std::list<RepoInfo> repos = knownRepositories();
1108 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1112 // they can be the same only if the provided is empty, that means
1113 // the provided repo has no alias
1115 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1118 // TODO match by url
1120 // we have a matcing repository, now we need to know
1121 // where it does come from.
1122 RepoInfo todelete = *it;
1123 if (todelete.filepath().empty())
1125 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1129 // figure how many repos are there in the file:
1130 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1131 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1133 // easy, only this one, just delete the file
1134 if ( filesystem::unlink(todelete.filepath()) != 0 )
1136 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1138 MIL << todelete.alias() << " sucessfully deleted." << endl;
1142 // there are more repos in the same file
1143 // write them back except the deleted one.
1145 //std::ofstream file(tmp.path().c_str());
1147 // assert the directory exists
1148 filesystem::assert_dir(todelete.filepath().dirname());
1150 std::ofstream file(todelete.filepath().c_str());
1152 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1153 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1155 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1156 fit != filerepos.end();
1159 if ( (*fit).alias() != todelete.alias() )
1160 (*fit).dumpRepoOn(file);
1164 CombinedProgressData subprogrcv(progress, 70);
1165 CombinedProgressData cleansubprogrcv(progress, 30);
1166 // now delete it from cache
1167 if ( isCached(todelete) )
1168 cleanCache( todelete, subprogrcv);
1169 // now delete metadata (#301037)
1170 cleanMetadata( todelete, cleansubprogrcv);
1171 MIL << todelete.alias() << " sucessfully deleted." << endl;
1173 } // else filepath is empty
1176 // should not be reached on a sucess workflow
1177 ZYPP_THROW(RepoNotFoundException(info));
1180 ////////////////////////////////////////////////////////////////////////////
1182 void RepoManager::modifyRepository( const std::string &alias,
1183 const RepoInfo & newinfo,
1184 const ProgressData::ReceiverFnc & progressrcv )
1186 RepoInfo toedit = getRepositoryInfo(alias);
1188 // check if the new alias already exists when renaming the repo
1189 if (alias != newinfo.alias())
1191 std::list<RepoInfo> repos = knownRepositories();
1192 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1196 if ( newinfo.alias() == (*it).alias() )
1197 ZYPP_THROW(RepoAlreadyExistsException(newinfo.alias()));
1201 if (toedit.filepath().empty())
1203 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1207 // figure how many repos are there in the file:
1208 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1210 // there are more repos in the same file
1211 // write them back except the deleted one.
1213 //std::ofstream file(tmp.path().c_str());
1215 // assert the directory exists
1216 filesystem::assert_dir(toedit.filepath().dirname());
1218 std::ofstream file(toedit.filepath().c_str());
1220 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1221 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1223 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1224 fit != filerepos.end();
1227 // if the alias is different, dump the original
1228 // if it is the same, dump the provided one
1229 if ( (*fit).alias() != toedit.alias() )
1230 (*fit).dumpRepoOn(file);
1232 newinfo.dumpRepoOn(file);
1237 ////////////////////////////////////////////////////////////////////////////
1239 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1240 const ProgressData::ReceiverFnc & progressrcv )
1242 std::list<RepoInfo> repos = knownRepositories();
1243 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1247 if ( (*it).alias() == alias )
1251 info.setAlias(info.alias());
1252 ZYPP_THROW(RepoNotFoundException(info));
1255 ////////////////////////////////////////////////////////////////////////////
1257 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1258 const url::ViewOption & urlview,
1259 const ProgressData::ReceiverFnc & progressrcv )
1261 std::list<RepoInfo> repos = knownRepositories();
1262 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1266 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1267 urlit != (*it).baseUrlsEnd();
1270 if ((*urlit).asString(urlview) == url.asString(urlview))
1275 info.setAlias(info.alias());
1276 info.setBaseUrl(url);
1277 ZYPP_THROW(RepoNotFoundException(info));
1280 ////////////////////////////////////////////////////////////////////////////
1282 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1284 return str << *obj._pimpl;
1287 /////////////////////////////////////////////////////////////////
1289 ///////////////////////////////////////////////////////////////////