You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1838 lines
55 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2013-2016 Mir Calculate. http://www.calculate-linux.org
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import sys
  17. import re
  18. from os import path
  19. from calculate.lib.cl_template import SystemIni
  20. from calculate.lib.cl_log import log
  21. from calculate.lib.datavars import (Variable, VariableError,
  22. ReadonlyVariable, ReadonlyTableVariable,
  23. TableVariable, FieldValue,
  24. HumanReadable, CriticalError,
  25. SimpleDataVars, DataVarsError)
  26. from calculate.lib.utils.binhosts import (Binhosts, PackagesIndex, HOURS,
  27. BinhostSignError)
  28. from calculate.lib.utils.files import readFile, listDirectory, process, pathJoin
  29. from calculate.lib.configparser import ConfigParser
  30. from calculate.lib.cl_lang import setLocalTranslate
  31. from calculate.lib.utils.text import simplify_profiles, _u8
  32. from calculate.lib.utils.git import Git, GitError
  33. from calculate.lib.utils.portage import ReposConf, PortageState
  34. from ..profile import (RepositoryStorageSet, DEFAULT_BRANCH,
  35. LocalStorage, ProfileRepository, CacheStorage)
  36. from calculate.lib.variables import linux as lib_linux
  37. from calculate.lib.variables import env
  38. from calculate.lib.variables import system as lib_system
  39. from calculate.update.update_info import UpdateInfo
  40. from itertools import chain
  41. from urlparse import urlparse
  42. import io
  43. import time
  44. _ = lambda x: x
  45. setLocalTranslate('cl_update3', sys.modules[__name__])
  46. class VariableAcUpdateSync(ReadonlyVariable):
  47. """
  48. Action variable which has value "up" for package install and
  49. install this package
  50. """
  51. def get(self):
  52. action = self.Get("cl_action")
  53. if action in ("sync",):
  54. if self.Get('cl_update_world'):
  55. return self.Get('cl_update_world')
  56. return ""
  57. class VariableClUpdateWorldDefault(Variable):
  58. """
  59. Ad-hoc
  60. """
  61. value = "update"
  62. class VariableClUpdateWorld(Variable):
  63. type = "choice"
  64. opt = ["--world"]
  65. syntax = "--{choice}-world"
  66. metavalue = "MODE"
  67. def init(self):
  68. self.help = ("'rebuild' - " + _("rebuild the system packages list") +
  69. ",\n'merge' - " + _("append the profile packages list") +
  70. ",\n'update' - " + _("update the system packages list"))
  71. self.label = _("System packages list")
  72. def get(self):
  73. return self.Get('cl_update_world_default')
  74. def choice(self):
  75. return [("rebuild", _("Rebuild")),
  76. ("merge", _("Merge")),
  77. ("update", _("Update"))]
  78. class VariableClRebuildWorldSet(Variable):
  79. """
  80. List of action update world, rebuild world,
  81. """
  82. type = "bool"
  83. opt = ["--rebuild-world"]
  84. untrusted = True
  85. value = "off"
  86. def init(self):
  87. self.help = _("Rebuild world")
  88. self.label = _("Rebuild world")
  89. class VariableClUpdateRevSet(Variable):
  90. """
  91. List of action update world, rebuild world,
  92. """
  93. type = "bool"
  94. opt = ["--update-rev"]
  95. untrusted = True
  96. value = "on"
  97. check_after = ["cl_update_sync_rep",
  98. "cl_update_metadata_force",
  99. "cl_update_other_set",
  100. "cl_update_eixupdate_force"]
  101. def init(self):
  102. self.help = _("make a revision update")
  103. self.label = _("Make a revision update")
  104. class VariableClUpdateRep(Variable):
  105. """
  106. Обновлять репозитории до конкретной ревизии или до последней
  107. """
  108. type = "choice"
  109. value = "rev"
  110. def choice(self):
  111. return ["last", "rev"]
  112. class VariableClUpdateRepData(ReadonlyTableVariable):
  113. """
  114. Информация о репозиториях
  115. """
  116. source = ['cl_update_rep_name',
  117. 'cl_update_rep_url',
  118. 'cl_update_rep_path',
  119. 'cl_update_rep_rev']
  120. class VariableClUpdateRepName(Variable):
  121. """
  122. Список имен используемых репозиториев
  123. """
  124. type = "list"
  125. value = []
  126. def humanReadable(self):
  127. return [x.capitalize() for x in self.Get()]
  128. class VariableClUpdateRepUrl(Variable):
  129. """
  130. Список путей до репозиториев
  131. """
  132. type = "list"
  133. value = []
  134. class VariableClUpdateLaymanStorage(Variable):
  135. """
  136. Путь к репозиториям
  137. """
  138. param_name = "storage"
  139. fallback_value = "var/lib/layman"
  140. def get(self):
  141. return pathJoin(self.Get('cl_chroot_path'), self.fallback_value)
  142. class VariableClUpdateReposStorage(Variable):
  143. """
  144. Путь к репозиториям
  145. """
  146. param_name = "storage"
  147. fallback_value = "var/db/repos"
  148. def get(self):
  149. return pathJoin(self.Get('cl_chroot_path'), self.fallback_value)
  150. class VariableClUpdateRepPath(ReadonlyVariable):
  151. """
  152. Пути до репозиториев
  153. """
  154. type = "list"
  155. mapPath = {'portage': 'usr/portage',
  156. 'gentoo': 'usr/portage'}
  157. def get(self):
  158. repPath = self.Get('cl_update_repos_storage')
  159. chroot_path = self.Get('cl_chroot_path')
  160. def generatePaths(names):
  161. for name in names:
  162. if name in self.mapPath:
  163. yield path.join(chroot_path, self.mapPath[name])
  164. else:
  165. yield path.join(repPath, name)
  166. return list(generatePaths(self.Get('cl_update_rep_name')))
  167. class VariableClUpdateRepRev(Variable):
  168. """
  169. Ревизии до которых необходимо обновить репозитории
  170. """
  171. type = "list"
  172. def get(self):
  173. cp = ConfigParser()
  174. revisions = self.Get('update.cl_update_binhost_revisions')
  175. if revisions:
  176. cp.read_string(unicode(revisions[0]))
  177. branch = self.Get('cl_update_branch')
  178. def generateBranch():
  179. for repname, branchname in zip(
  180. self.Get('cl_update_rep_name'),
  181. self.Get('cl_update_branch_name')):
  182. if branchname == Git.Reference.Tag:
  183. yield cp.get("vcs", repname, fallback=branch)
  184. else:
  185. yield branchname
  186. return list(generateBranch())
  187. class VariableClUpdateBranch(Variable):
  188. """
  189. Ветка на которую будет обновляться репозиторий если
  190. не используется синхронизация по тэгам
  191. """
  192. value = Git.Reference.Master
  193. arch_var = "main.os_arch_machine"
  194. def get(self):
  195. arch = self.Get(self.arch_var)
  196. if arch == "x86_64":
  197. return "master"
  198. else:
  199. return "master"
  200. class VariableClUpdateBranchData(TableVariable):
  201. """
  202. Выбор веток репозиториев до которых необходимо обновиться
  203. """
  204. opt = ["--branch"]
  205. metavalue = 'REFS'
  206. untrusted = True
  207. source = ["cl_update_branch_rep",
  208. "cl_update_branch_name"]
  209. def init(self):
  210. self.help = _("set references for repository (REPOSITORY:REF)")
  211. self.label = _("Repositories references")
  212. def raiseReadonlyIndexError(self, fieldname="", variablename="", value=""):
  213. """
  214. Неизвестный оврелей
  215. """
  216. raise VariableError(_("Repository %s not found") % value)
  217. class VariableClUpdateBranchRep(ReadonlyVariable):
  218. """
  219. Список доступных репозиторием
  220. """
  221. type = "list"
  222. def init(self):
  223. self.label = _("Repository")
  224. def get(self):
  225. return self.Get('cl_update_rep_name')
  226. class VariableClUpdateBinhostsInfo(ReadonlyVariable):
  227. """
  228. Объект для получения информации о серверах обновлений
  229. """
  230. type = Variable.Types.Object
  231. def get(self):
  232. last_ts = self.Get('cl_update_last_timestamp')
  233. if self.GetBool('cl_update_binhost_stable_opt_set'):
  234. binhost_list = self.Get('cl_update_binhost_list')
  235. else:
  236. binhost_list = self.Get('cl_update_binhost_unstable_list')
  237. return Binhosts(
  238. self.GetInteger('cl_update_binhost_timeout'),
  239. self.Get('cl_update_binhost_revision_path'),
  240. self.Get('cl_update_binhost_timestamp_path'),
  241. last_ts, binhost_list,
  242. self.Get('os_arch_machine'),
  243. gpg=self.Get('cl_update_gpg'))
  244. class VariableClUpdateBinhostData(ReadonlyTableVariable):
  245. """
  246. Таблица содержащая
  247. binhost/содержимое файла ревизий/время доступа
  248. """
  249. source = ["cl_update_binhost_host",
  250. "cl_update_binhost_revisions",
  251. "cl_update_binhost_timestamp",
  252. "cl_update_binhost_time"]
  253. def get(self, hr=HumanReadable.No):
  254. return Variable.EmptyTable
  255. class VariableClUpdateBinhostRecheckSet(Variable):
  256. """
  257. Принудительно обновить binhost
  258. """
  259. type = Variable.Types.Boolean
  260. value = Variable.Off
  261. opt = ["--scan"]
  262. def init(self):
  263. self.help = _("search for the most appropriate update server")
  264. self.label = _("Search for the most appropriate update server")
  265. class VariableClUpdateBinhostHost(FieldValue, Variable):
  266. """
  267. Список имен прочих репозиториев
  268. """
  269. type = "list"
  270. source_variable = "cl_update_binhost_data"
  271. column = 0
  272. class VariableClUpdateBinhostRevisions(FieldValue, Variable):
  273. """
  274. Список имен прочих репозиториев
  275. """
  276. type = "list"
  277. source_variable = "cl_update_binhost_data"
  278. column = 1
  279. class VariableClUpdateBinhostTimestamp(FieldValue, Variable):
  280. """
  281. Список имен прочих репозиториев
  282. """
  283. type = "list"
  284. source_variable = "cl_update_binhost_data"
  285. column = 2
  286. class VariableClUpdateBinhostTime(FieldValue, Variable):
  287. """
  288. Список имен прочих репозиториев
  289. """
  290. type = "list"
  291. source_variable = "cl_update_binhost_data"
  292. column = 3
  293. class VariableClUpdateLastTimestamp(ReadonlyVariable):
  294. """
  295. Текущий timestamp
  296. """
  297. def get(self):
  298. ini = SystemIni(self.parent)
  299. return ini.getVar('system', 'last_update') or "0"
  300. class VariableClUpdateSettingsChangesSet(Variable):
  301. """
  302. Определить были ли изменения в /etc/portage, /var/log/emerge.log
  303. """
  304. type = Variable.Types.Boolean
  305. def get(self):
  306. ini = SystemIni(self.parent)
  307. old_portage_state_hash = ini.getVar('system', 'portage_hash') or ""
  308. ps = PortageState()
  309. new_portage_state_hash = ps.get_state()
  310. return "on" if new_portage_state_hash != old_portage_state_hash else "off"
  311. class VariableClUpdateBranchName(Variable):
  312. """
  313. Список доступных репозиторием
  314. """
  315. type = "choiceedit-list"
  316. def init(self):
  317. self.label = _("Reference")
  318. def choice(self):
  319. return [
  320. Git.Reference.Tag,
  321. Git.Reference.Master,
  322. Git.Reference.Develop,
  323. Git.Reference.Update]
  324. def get(self):
  325. if self.GetBool('cl_update_usetag_set'):
  326. return [Git.Reference.Tag for x in self.Get('cl_update_rep_name')]
  327. else:
  328. branch = self.Get('cl_update_branch')
  329. return [branch for x in self.Get('cl_update_rep_name')]
  330. class VariableClUpdateSyncRep(Variable):
  331. """
  332. Обновляемый репозиторий
  333. """
  334. type = "choice-list"
  335. element = "selecttable"
  336. opt = ["-r", "--repositories"]
  337. metavalue = "REPOSITORIES"
  338. untrusted = True
  339. @property
  340. def rep_name(self):
  341. return self.Get('update.cl_update_rep_name')
  342. def init(self):
  343. self.help = _("synchronized repositories (all by default)")
  344. self.label = _("Synchronized repositories")
  345. def set(self, value):
  346. orderList = self.rep_name
  347. return sorted(value, key=lambda x:
  348. (orderList.index(x) if x in orderList else -1), reverse=True)
  349. def get(self):
  350. return list(reversed(self.rep_name))
  351. def choice(self):
  352. return [ (x, x.capitalize()) for x in self.rep_name]
  353. class VariableClUpdateSyncOverlayRep(ReadonlyVariable):
  354. """
  355. Обновляемые репозитории (исключая portage)
  356. """
  357. type = "list"
  358. def get(self):
  359. return filter(lambda x: x not in ("portage", "gentoo"),
  360. self.Get('cl_update_sync_rep'))
  361. class VariableClUpdateOutdateSet(ReadonlyVariable):
  362. """
  363. Флаг устанавливаемый в ходе обновления репозиториев,
  364. сообщающий что хотя бы один из запланированных репозиториев
  365. обновлен и следует обновляет различные метаданные
  366. Если обновляются прочие оверлеи - данные считаются что устарели
  367. """
  368. type = "bool"
  369. def get(self):
  370. if (self.Get('cl_update_other_set') == 'on' and
  371. self.Get('cl_update_other_rep_name')):
  372. return "on"
  373. return "off"
  374. class VariableClUpdateMetadataForce(Variable):
  375. """
  376. Принудительное действие с метаданными
  377. """
  378. type = "choice"
  379. value = "auto"
  380. opt = ["--update-metadata"]
  381. syntax = "--{choice}-update-metadata"
  382. metavalue = "MODE"
  383. # untrusted = True
  384. def init(self):
  385. self.help = ("'force' - " + _("force the update ebuilds metadata") +
  386. ",\n'skip' - " + _("skip the ebuild metadata update") +
  387. ",\n'auto' - " + _("update metadata if it is outdated"))
  388. self.label = _("Update metadata")
  389. def choice(self):
  390. return [("force", _("Force")),
  391. ("skip", _("Skip")),
  392. ("auto", _("If needed"))]
  393. class VariableClUpdateEgencacheForce(Variable):
  394. """
  395. Принудительное выполнение egencache
  396. """
  397. type = "choice"
  398. value = "auto"
  399. opt = ["--egencache"]
  400. syntax = "--{choice}-egencache"
  401. metavalue = "MODE"
  402. # untrusted = True
  403. def init(self):
  404. self.help = (
  405. "'force' - " + _("force the update of the overlays cache") +
  406. ",\n'skip' - " + _("skip the update of the overlays cache") +
  407. ",\n'auto' - " + _("update the overlays cache if outdated"))
  408. self.label = _("Update the overlays cache")
  409. def choice(self):
  410. return [("force", _("Force")),
  411. ("skip", _("Skip")),
  412. ("auto", _("If needed"))]
  413. class VariableClUpdateEixupdateForce(Variable):
  414. """
  415. Принудительное действие с eix-update
  416. """
  417. type = "choice"
  418. value = "auto"
  419. opt = ["--eix-update"]
  420. syntax = "--{choice}-eix-update"
  421. metavalue = "MODE"
  422. # untrusted = True
  423. def init(self):
  424. self.help = ("'force' - " + _("force the eix cache update") +
  425. ",\n'skip' - " + _("skip the eix cache update") +
  426. ",\n'auto' - " + _("update the eix cache if it "
  427. "is outdated"))
  428. self.label = _("Update the eix cache")
  429. def choice(self):
  430. return [("force", _("Force")),
  431. ("skip", _("Skip")),
  432. ("auto", _("If needed"))]
  433. class VariableClUpdateGpgForce(Variable):
  434. """
  435. Принудительное действие с eix-update
  436. """
  437. type = "choice"
  438. value = "force"
  439. opt = ["--check-sign"]
  440. syntax = "--{choice}-check-sign"
  441. metavalue = "MODE"
  442. # untrusted = True
  443. def init(self):
  444. self.help = ("'force' - " + _("force check Package signature") +
  445. ",\n'skip' - " + _("skip check Package signature") +
  446. ",\n'auto' - " + _("check signature if system has public keys"))
  447. self.label = _("Check Package signature")
  448. def choice(self):
  449. return [("force", _("Force")),
  450. ("skip", _("Skip")),
  451. ("auto", _("If has passibility"))]
  452. class VariableClUpdateOtherSet(Variable):
  453. """
  454. Обновить остальные оверлеи
  455. """
  456. type = "bool"
  457. value = "off"
  458. opt = ["-o", "--update-other"]
  459. def init(self):
  460. self.help = _("update other overlays")
  461. self.label = _("Update other overlays")
  462. class VariableClUpdateOtherRepData(ReadonlyTableVariable):
  463. """
  464. Информация о прочих репозиториях
  465. """
  466. source = ['cl_update_other_rep_name',
  467. 'cl_update_other_rep_path']
  468. def generator(self):
  469. repNames = self.Get('update.cl_update_rep_name')
  470. chroot_path = self.Get('cl_chroot_path')
  471. reposconf = ReposConf(
  472. self.Get('update.cl_update_reposconf'),
  473. self.Get('update.cl_update_reposconf_dir'),
  474. prefix=chroot_path)
  475. for rname, rpath in reposconf.get_other_repositories():
  476. yield (_u8(rname), pathJoin(chroot_path, _u8(rpath)))
  477. def get(self, hr=HumanReadable.No):
  478. return list(self.generator())
  479. class VariableClUpdateOtherRepName(FieldValue, ReadonlyVariable):
  480. """
  481. Список имен прочих репозиториев
  482. """
  483. type = "list"
  484. source_variable = "cl_update_other_rep_data"
  485. column = 0
  486. class VariableClUpdateOtherRepPath(FieldValue, ReadonlyVariable):
  487. """
  488. Список путей до прочих репозиториев
  489. """
  490. type = "list"
  491. source_variable = "cl_update_other_rep_data"
  492. column = 1
  493. class VariableClUpdateReposconfDir(ReadonlyVariable):
  494. """
  495. Директорий с файлами, описывающими репозитории
  496. """
  497. def get(self):
  498. chroot = self.Get('cl_chroot_path')
  499. return path.join(chroot, '/etc/portage/repos.conf')
  500. class VariableClUpdateReposconf(ReadonlyVariable):
  501. """
  502. Путь конфигурационного файла repos.conf, содержащего Calculate репозитории
  503. """
  504. value_format = "{update.cl_update_reposconf_dir}/zz-calculate.conf"
  505. class VariableClUpdatePretendSet(Variable):
  506. """
  507. Запустить предварительную проверку на обновления
  508. """
  509. type = "bool"
  510. value = "off"
  511. opt = ["-p", "--pretend"]
  512. def init(self):
  513. self.label = _("Pretend a package update")
  514. self.help = _("instead of actually performing the update, "
  515. "simply display the list of packages that "
  516. "will be installed")
  517. class VariableClUpdateSyncOnlySet(Variable):
  518. """
  519. Не выполнять установку/обновление пакетов при обновлении
  520. """
  521. type = "bool"
  522. value = "off"
  523. opt = ["-s", "--sync-only"]
  524. def init(self):
  525. self.label = _("Only synchronize repositories")
  526. self.help = _("do not update packages")
  527. def check(self, value):
  528. if (value == "on" and self.Get('cl_rebuild_world_set') != 'on' and
  529. not self.Get('cl_update_sync_rep') and
  530. self.Get('cl_update_other_set') == 'off' and
  531. self.Get('cl_update_rev_set') == 'off' and
  532. self.Get('cl_update_metadata_force') != "force" and
  533. self.Get('cl_update_eixupdate_force') != "force"):
  534. raise VariableError(_("Select at least one sync repository"))
  535. class VariableClUpdateWaitAnotherSet(Variable):
  536. """
  537. Ждать завершения другого процесса обновления
  538. """
  539. type = "bool"
  540. value = "on"
  541. opt = ["--wait-another-update"]
  542. def init(self):
  543. self.label = _("Wait for another update to be complete")
  544. self.help = _("wait until the running update is finished")
  545. class VariableClUpdateProfileStorage(ReadonlyVariable):
  546. type = "object"
  547. def get(self):
  548. git = self.Get('cl_update_git')
  549. return RepositoryStorageSet(
  550. LocalStorage(git, '/var/db/repos'),
  551. CacheStorage(git, '/var/calculate/tmp/update'))
  552. class VariableClUpdateGit(ReadonlyVariable):
  553. type = "object"
  554. def get(self):
  555. sshkey = self.Get('update.cl_update_sshkey_path')
  556. if path.exists(sshkey):
  557. return Git(sshkey)
  558. else:
  559. return Git()
  560. class VariableClUpdateRepHost(Variable):
  561. type = "list"
  562. value = ['calculate']
  563. class VariableClUpdateRepHostUrl(Variable):
  564. type = "list"
  565. value = ['git://github.com/calculatelinux/%s.git']
  566. class VariableClUpdateProfileDatavars(ReadonlyVariable):
  567. type = "object"
  568. profile = "cl_update_profile_system"
  569. profiles_path = "cl_update_profile_path"
  570. profiles_shortname = "cl_update_profile_shortname"
  571. def get(self):
  572. profile = self.Get(self.profile)
  573. path_profile = self.Select(self.profiles_path,
  574. where=self.profiles_shortname,
  575. eq=profile, limit=1)
  576. if path_profile:
  577. return DataVarsUpdateProfile(path_profile)
  578. return ""
  579. class VariableClUpdateProfileLinuxFullname(ReadonlyVariable):
  580. """
  581. Имя системы в профиле
  582. """
  583. def init(self):
  584. self.label = _("Distribution name")
  585. datavars = "cl_update_profile_datavars"
  586. def get(self):
  587. dv = self.Get(self.datavars)
  588. if dv:
  589. try:
  590. subname = dv.Get('os_linux_subname')
  591. linuxname = dv.Get('os_linux_name')
  592. if subname:
  593. return "%s %s" % (linuxname, subname)
  594. return linuxname
  595. except DataVarsError:
  596. raise VariableError("Wrong Calculate Linux profile")
  597. return ""
  598. class VariableClUpdateProfileDependData(ReadonlyTableVariable):
  599. """
  600. Зависимые репозитории
  601. """
  602. source = ['cl_update_profile_depend_name',
  603. 'cl_update_profile_depend_url']
  604. datavars = "cl_update_profile_datavars"
  605. def init(self):
  606. self.label = _("Used repositories")
  607. @staticmethod
  608. def url_like(url1, url2):
  609. match1 = VariableClUpdateProfileUrl.re_url.search(url1)
  610. match2 = VariableClUpdateProfileUrl.re_url.search(url2)
  611. if match1 and match2:
  612. return match1.group(2).lower() == match2.group(2).lower()
  613. return False
  614. def get(self, hr=HumanReadable.No):
  615. dv = self.Get(self.datavars)
  616. if dv:
  617. if hr == HumanReadable.Yes:
  618. return reversed(zip([x.capitalize() for x in dv.Get('cl_update_rep_name')],
  619. dv.Get('cl_update_rep_url')))
  620. else:
  621. return reversed(zip(dv.Get('cl_update_rep_name'),
  622. dv.Get('cl_update_rep_url')))
  623. return ""
  624. setValue = Variable.setValue
  625. class VariableClUpdateTemplatesLocate(Variable):
  626. """
  627. Выбранные типы хранилищ шаблонов
  628. """
  629. type = "choice-list"
  630. element = "selecttable"
  631. opt = ["-T", "--templates"]
  632. metavalue = "TEMPLATES"
  633. untrusted = True
  634. check_after = ['cl_update_profile_system']
  635. profile_datevars = "update.cl_update_profile_datavars"
  636. descriptionMap = {'overlay': _('Overlay templates'),
  637. 'local': _('Local templates'),
  638. 'calculate': _("Calculate overlay templates"),
  639. 'distros': _('Distribution templates'),
  640. 'distro': _('Distribution templates'),
  641. 'remote': _('Remote templates'),
  642. 'clt': _('clt templates')}
  643. def init(self):
  644. self.label = _("Templates location")
  645. self.help = _("select the location for templates %s") \
  646. % ",".join(self.get())
  647. def get(self):
  648. dv = self.Get(self.profile_datevars)
  649. if dv:
  650. return dv.Get('cl_template_location') + ['clt']
  651. else:
  652. return self.Get('cl_templates_locate')
  653. def choice(self):
  654. descr = lambda x: self.descriptionMap.get(x,
  655. _("%s overlay templates" % x))
  656. return map(lambda x: (x, descr(x)), self.get())
  657. class VariableClUpdateProfileDependName(FieldValue, ReadonlyVariable):
  658. type = "list"
  659. source_variable = "cl_update_profile_depend_data"
  660. column = 0
  661. def init(self):
  662. self.label = _("Name")
  663. class VariableClUpdateProfileDependUrl(FieldValue, ReadonlyVariable):
  664. type = "list"
  665. source_variable = "cl_update_profile_depend_data"
  666. column = 1
  667. def init(self):
  668. self.label = _("URL")
  669. class VariableClUpdateProfileRepName(ReadonlyVariable):
  670. type = "list"
  671. def get(self):
  672. dv = self.Get('cl_update_profile_datavars')
  673. if dv:
  674. return dv.Get('cl_update_rep_name')
  675. return []
  676. class VariableClUpdateProfileSyncRep(ReadonlyVariable):
  677. type = "list"
  678. def get(self):
  679. return list(reversed(self.Get('cl_update_profile_rep_name')))
  680. class VariableClUpdateProfileRepUrl(ReadonlyVariable):
  681. type = "list"
  682. def get(self):
  683. dv = self.Get('cl_update_profile_datavars')
  684. if dv:
  685. return dv.Get('cl_update_rep_url')
  686. return []
  687. class VariableClUpdateProfileLinuxVer(ReadonlyVariable):
  688. """
  689. Имя системы в профиле
  690. """
  691. def init(self):
  692. self.label = _("System profile version")
  693. def get(self):
  694. dv = self.Get('cl_update_profile_datavars')
  695. if dv:
  696. return dv.Get('os_linux_ver')
  697. return ""
  698. class VariableClUpdateProfileLinuxName(ReadonlyVariable):
  699. """
  700. Имя системы в профиле
  701. """
  702. def get(self):
  703. dv = self.Get('cl_update_profile_datavars')
  704. if dv:
  705. dv.Get('os_linux_name')
  706. return ""
  707. class VariableClUpdateProfileUrl(Variable):
  708. """
  709. URL текущего репозитория
  710. """
  711. untrusted = True
  712. check_after = ["cl_update_profile_branch"]
  713. check_action = "update_profile"
  714. opt = ["--url"]
  715. metavalue = "URL"
  716. profile = "cl_profile_system"
  717. branch = "cl_update_profile_branch"
  718. storage = "cl_update_profile_storage"
  719. default_url = "git://github.com/calculatelinux/distros.git"
  720. profiles_shortname = 'cl_update_profile_shortname'
  721. @property
  722. def current_root(self):
  723. return '/'
  724. @property
  725. def rep_names(self):
  726. return self.Get("update.cl_update_rep_name")
  727. def init(self):
  728. self.label = _("Profile repository")
  729. self.help = _("set the profile repository")
  730. re_url = re.compile(
  731. r"^(?:(%s)://)?((?:git@)?\w[\w\./:-]+?\w)(\.git)?$" % "|".join(
  732. ["http", "https", "git", "ssh"]))
  733. re_shortname = re.compile('^(?:([\w\.-]+):)?([\w\.-]+)$')
  734. @classmethod
  735. def normalize_url(cls, url):
  736. url = Git.normalize_url(url)
  737. if not url:
  738. raise VariableError(_("Wrong repository URL"))
  739. return url
  740. def url_by_shortname(self, value):
  741. match = self.re_shortname.match(value)
  742. if not match.group(1):
  743. template = self.Get('update.cl_update_rep_host_url')
  744. if template:
  745. template = template[0]
  746. else:
  747. template = self.Select('update.cl_update_rep_host_url',
  748. where='update.cl_update_rep_host',
  749. eq=match.group(1), limit=1)
  750. if not template:
  751. raise VariableError(_("Failed to determine the repository host"))
  752. try:
  753. return template % match.group(2)
  754. except TypeError:
  755. raise VariableError(_("Failed to determine the repository host"))
  756. def set(self, value):
  757. if self.re_shortname.match(value):
  758. value = self.url_by_shortname(value)
  759. return self.normalize_url(value)
  760. def check(self, value):
  761. if not value:
  762. raise VariableError("Need to specify profile repository")
  763. try:
  764. branch = self.Get(self.branch)
  765. self.Get(self.storage).get_profiles(value, branch)
  766. except GitError as e:
  767. raise VariableError(str(e))
  768. if not self.Get(self.profiles_shortname):
  769. raise VariableError(_("Repository %s has no profiles") %
  770. value.encode('utf-8'))
  771. def get(self):
  772. try:
  773. profile = self.Get(self.profile)
  774. if profile:
  775. while (profile != self.current_root and
  776. ".git" not in listDirectory(profile) and
  777. "repo_name" not in listDirectory(
  778. path.join(profile,"profiles"))):
  779. profile = path.dirname(profile)
  780. if profile == self.current_root:
  781. return self.default_url
  782. if ".git" not in listDirectory(profile):
  783. repo_name = readFile(path.join(
  784. profile,"profiles/repo_name")).strip()
  785. if (repo_name in self.rep_names and
  786. self.Get('cl_action') == self.check_action):
  787. raise CriticalError(
  788. _("You need to update the repositories before "
  789. "you change the profile"))
  790. return Git.get_url(profile, "origin") or self.default_url
  791. except CriticalError as e:
  792. raise VariableError(str(e))
  793. except Exception as e:
  794. pass
  795. return self.default_url
  796. class VariableClUpdateProfileRepoName(ReadonlyVariable):
  797. def init(self):
  798. self.label = _("Repository name")
  799. storage = "cl_update_profile_storage"
  800. url = "cl_update_profile_url"
  801. def get(self):
  802. rep_set = self.Get(self.storage)
  803. url = self.Get(self.url)
  804. if url:
  805. rep = rep_set.get_repository(url, branch=None)
  806. if rep:
  807. return rep.repo_name
  808. return ""
  809. class VariableClUpdateProfileBranch(Variable):
  810. """
  811. Текущий репозиторий
  812. """
  813. untrusted = True
  814. type = "edit"
  815. opt = ["--branch"]
  816. metavalue = "BRANCH"
  817. storage = "cl_update_profile_storage"
  818. url = "cl_update_profile_url"
  819. def init(self):
  820. self.label = _("Repository branch")
  821. self.help = _("set the repository branch")
  822. def get(self):
  823. arch = self.Get("main.os_arch_machine")
  824. if arch == "x86_64":
  825. return "master"
  826. else:
  827. return "master"
  828. class VariableClProfileRepository(ReadonlyVariable):
  829. """
  830. Репозиторий из которого будут получены профили
  831. """
  832. type = "object"
  833. def get(self):
  834. try:
  835. git = self.Get('cl_update_git')
  836. profile_dn = self.Get('cl_profile_system')
  837. while profile_dn != '/' and ".git" not in listDirectory(profile_dn):
  838. profile_dn = path.dirname(profile_dn)
  839. if profile_dn == '/':
  840. return ""
  841. ls = LocalStorage(git, path.dirname(profile_dn))
  842. return ProfileRepository(git, path.basename(profile_dn), ls)
  843. except Exception:
  844. return ""
  845. class VariableClProfileData(ReadonlyTableVariable):
  846. """
  847. Таблица данных о текущих профилях системы
  848. """
  849. source = []
  850. repository = "cl_profile_repository"
  851. def profile_filter(self, profiles):
  852. arch = self.Get('os_arch_machine_gentoo')
  853. return [x for x in profiles if x.arch == arch]
  854. def get(self, hr=HumanReadable.No):
  855. rep = self.Get(self.repository)
  856. if not rep:
  857. return [[]]
  858. profiles = rep.get_profiles()
  859. if not profiles:
  860. return [[]]
  861. repo_name = profiles[0].repository.repo_name
  862. filtered_profiles = self.profile_filter(profiles)
  863. full_name = [x.profile for x in filtered_profiles]
  864. profile_path = [x.path for x in filtered_profiles]
  865. profile_arch = [x.arch for x in filtered_profiles]
  866. short_name = simplify_profiles(full_name)
  867. full_name = ["%s:%s" % (repo_name, x) for x in full_name]
  868. return zip(full_name,
  869. short_name,
  870. profile_path,
  871. profile_arch)
  872. setValue = Variable.setValue
  873. class VariableClUpdateProfileRepository(ReadonlyVariable):
  874. """
  875. Репозиторий из которого будет извлечён список профилей
  876. """
  877. type = "object"
  878. url = "cl_update_profile_url"
  879. storage = "cl_update_profile_storage"
  880. branch = "cl_update_profile_branch"
  881. sync_set = "update.cl_update_profile_sync_set"
  882. def get(self):
  883. url = self.Get(self.url)
  884. if not url:
  885. return ""
  886. try:
  887. rep_set = self.Get(self.storage)
  888. branch = self.Get(self.branch)
  889. rep = rep_set.get_repository(url, branch=None)
  890. if rep and self.Get(self.sync_set) == 'on':
  891. rep.sync()
  892. return rep_set.get_repository(url, branch=None) or ""
  893. except GitError:
  894. return ""
  895. class VariableClUpdateProfileRepositoryName(ReadonlyVariable):
  896. """
  897. Название репозитория, из которого будут извлечены профили
  898. """
  899. def get(self):
  900. rep = self.Get('cl_update_profile_repository')
  901. if rep:
  902. return rep.repo_name
  903. return ""
  904. class VariableClUpdateProfileData(VariableClProfileData):
  905. source = ["cl_update_profile_fullname",
  906. "cl_update_profile_shortname",
  907. "cl_update_profile_path",
  908. "cl_update_profile_arch"]
  909. repository = "cl_update_profile_repository"
  910. class VariableClUpdateProfileFullname(FieldValue, ReadonlyVariable):
  911. """
  912. Полное название профиля
  913. """
  914. type = "list"
  915. source_variable = "cl_update_profile_data"
  916. column = 0
  917. class VariableClUpdateProfileShortname(FieldValue, ReadonlyVariable):
  918. """
  919. Упрощенное название профиля
  920. """
  921. type = "list"
  922. source_variable = "cl_update_profile_data"
  923. column = 1
  924. class VariableClUpdateProfilePath(FieldValue, ReadonlyVariable):
  925. """
  926. Путь от корня до профиля
  927. """
  928. type = "list"
  929. source_variable = "cl_update_profile_data"
  930. column = 2
  931. class VariableClUpdateProfileArch(FieldValue, ReadonlyVariable):
  932. """
  933. Архитектура профиля
  934. """
  935. type = "list"
  936. source_variable = "cl_update_profile_data"
  937. column = 3
  938. class VariableClUpdateProfileSystem(Variable):
  939. """
  940. Профиль системы (симлинк /etc/make.profile')
  941. """
  942. type = "choice"
  943. opt = ["cl_update_profile_system"]
  944. untrusted = True
  945. metavalue = "PROFILE"
  946. profiles_path = "cl_update_profile_path"
  947. profiles_shortname = "cl_update_profile_shortname"
  948. profiles_fullname = "cl_update_profile_fullname"
  949. profiles_arch = "cl_update_profile_arch"
  950. profile = "cl_profile_system"
  951. url = "cl_update_profile_url"
  952. gentoo_arch = 'os_arch_machine_gentoo'
  953. def init(self):
  954. self.label = _("System profile")
  955. self.help = _("set the system profile")
  956. def check(self, profile):
  957. if not profile:
  958. raise VariableError(_("You must specify the profile"))
  959. path_profile = self.Select(self.profiles_path,
  960. where=self.profiles_shortname,
  961. eq=profile, limit=1)
  962. profile_fullname = self.Select(self.profiles_fullname,
  963. where=self.profiles_shortname,
  964. eq=profile, limit=1)
  965. if path_profile:
  966. dv = DataVarsUpdateProfile(path_profile)
  967. if ":" in profile_fullname:
  968. repo_name = profile_fullname.partition(":")[0]
  969. else:
  970. repo_name = ""
  971. try:
  972. if (not dv.Get('cl_update_rep_name') or
  973. not dv.Get('cl_update_rep_url')):
  974. raise VariableError(
  975. _("Repository variables "
  976. "were not configured for the profile"))
  977. if not dv.Get('os_linux_name'):
  978. raise VariableError("")
  979. if repo_name not in list(dv.Get('cl_update_rep_name')):
  980. raise VariableError(
  981. _("Overlay %s is not specified "
  982. "in cl_update_rep_name") % repo_name)
  983. except (DataVarsError, VariableError) as e:
  984. if str(e):
  985. message = ". " + str(e)
  986. else:
  987. message = ""
  988. raise VariableError(_("The selected profile is not Calculate")
  989. + message)
  990. else:
  991. raise VariableError(_("Wrong Calculate profile"))
  992. def get(self):
  993. try:
  994. profile_system = self.Get(self.profile)
  995. profile = self.Select(self.profiles_shortname,
  996. where=self.profiles_path,
  997. eq=profile_system, limit=1)
  998. if profile:
  999. return profile
  1000. except VariableError:
  1001. pass
  1002. shortname = self.Get(self.profiles_shortname)
  1003. if len(shortname) == 1:
  1004. return shortname[0]
  1005. return ""
  1006. def choice(self):
  1007. url = self.Get(self.url)
  1008. if not url:
  1009. return []
  1010. arch = self.Get(self.gentoo_arch)
  1011. profiles = zip(*self.Select([self.profiles_shortname,
  1012. self.profiles_fullname],
  1013. where=self.profiles_arch, eq=arch))
  1014. if profiles:
  1015. short_name, full_name = profiles
  1016. return zip(short_name, full_name)
  1017. return []
  1018. class DataVarsUpdateProfile(SimpleDataVars):
  1019. """
  1020. Упрощенная модель переменных для получения данных с удаленного профиля
  1021. """
  1022. source = ['cl_update_rep_name',
  1023. 'cl_update_rep_url',
  1024. 'cl_update_rep_path',
  1025. 'cl_update_rep_rev',
  1026. 'cl_update_branch_name']
  1027. def __init__(self, profile, chroot_path='/', recheck=None, stable=None):
  1028. SimpleDataVars.__init__(
  1029. self,
  1030. lib_linux.VariableOsLinuxName(),
  1031. lib_linux.VariableOsLinuxShortname(),
  1032. lib_linux.VariableOsLinuxSubname(),
  1033. lib_linux.VariableOsLinuxVer(),
  1034. lib_linux.VariableClProfileSystem(),
  1035. lib_system.VariableOsArchMachine(),
  1036. env.VariableClRepositoryData(),
  1037. env.VariableClRepositoryName(),
  1038. env.VariableClRepositoryLocation(),
  1039. env.VariableClChrootPath(),
  1040. env.VariableClTemplateLocation(),
  1041. env.VariableClTemplatePath(),
  1042. env.VariableClEmergeConfig(systemRoot=chroot_path),
  1043. env.VariableClEmergeInfo(systemRoot=chroot_path),
  1044. env.VariableClFeatures(),
  1045. env.VariableClMakeProfile(),
  1046. env.VariableClEbuildPhase(),
  1047. VariableClUpdateReposStorage(section="update"),
  1048. VariableClUpdateLaymanStorage(section="update"),
  1049. VariableClUpdateReposconf(section="update"),
  1050. VariableClUpdateReposconfDir(section="update"),
  1051. VariableClUpdateRepData(section="update"),
  1052. VariableClUpdateRepPath(section="update"),
  1053. VariableClUpdateRepRev(section="update"),
  1054. VariableClUpdateBranch(section="update"),
  1055. VariableClUpdateBranchName(section="update"),
  1056. VariableClUpdateUsetagSet(section="update"),
  1057. VariableClUpdateRepName(section="update"),
  1058. VariableClUpdateRep(section="update"),
  1059. VariableClUpdateRepUrl(section="update"),
  1060. VariableClUpdateBinhost(section="update"),
  1061. VariableClUpdateBinhostData(section="update"),
  1062. VariableClUpdateBinhostHost(section="update"),
  1063. VariableClUpdateBinhostRecheckSet(section="update"),
  1064. VariableClUpdateBinhostRevisions(section="update"),
  1065. VariableClUpdateBinhostTime(section="update"),
  1066. VariableClUpdateBinhostTimestamp(section="update"),
  1067. VariableClUpdateLastTimestamp(section="update"),
  1068. VariableClUpdateBinhostTimeout(section="update"),
  1069. VariableClUpdateBinhostTimestampPath(section="update"),
  1070. VariableClUpdateBinhostList(section="update"),
  1071. VariableClUpdateBinhostUnstableList(section="update"),
  1072. VariableClUpdateBinhostStableSet(section="update"),
  1073. VariableClUpdateBinhostStableOptSet(section="update"),
  1074. VariableClUpdateBinhostRevisionPath(section="update"),
  1075. )
  1076. self['cl_profile_system'] = profile
  1077. self['cl_chroot_path'] = chroot_path
  1078. if recheck is not None:
  1079. self['cl_update_binhost_recheck_set'] = recheck
  1080. if stable is not None:
  1081. self['cl_update_binhost_stable_opt_set'] = stable
  1082. self.flIniFileFrom(profile)
  1083. def __repr__(self):
  1084. return "Profile variables"
  1085. class VariableClUpdateProfileSyncSet(Variable):
  1086. """
  1087. Синхронизировать репозиторий перед сменой профиля
  1088. """
  1089. type = "bool"
  1090. value = "off"
  1091. opt = ["-u", "--update-cache"]
  1092. def init(self):
  1093. self.label = _("Update the cache")
  1094. self.help = _("Update the cache")
  1095. class VariableClUpdateAutocheckSet(Variable):
  1096. """
  1097. Выполнять/невыполнять автопроверку обновлений
  1098. """
  1099. type = "bool"
  1100. value = "on"
  1101. opt = ["-a", "--autocheck"]
  1102. def init(self):
  1103. self.label = _("Automatically check updates")
  1104. self.help = _("automatically check updates")
  1105. class VariableClUpdateAutocheckInterval(Variable):
  1106. """
  1107. Интервал выполнения проверки
  1108. """
  1109. type = "choiceedit"
  1110. opt = ["-I", "--autocheck-interval"]
  1111. metavalue = "INTERVAL"
  1112. def init(self):
  1113. self.label = _("Interval for the updates checking")
  1114. self.help = _("set interval for the updates checking")
  1115. def choice(self):
  1116. return [["6h", _("every six hours")],
  1117. ["12h", _("every twelve hours")],
  1118. ["1d", _("daily")]]
  1119. class VariableClUpdateAutocheckScheduleSet(Variable):
  1120. """
  1121. Запустить проверку только если со времени последнего запуска прошло
  1122. необходимое время
  1123. """
  1124. type = "bool"
  1125. value = "off"
  1126. opt = ["--schedule"]
  1127. def init(self):
  1128. self.label = _("Consider the autocheck schedule")
  1129. self.help = _("consider the autocheck schedule")
  1130. class VariableClUpdateEmergelistSet(Variable):
  1131. """
  1132. Вывести список пакетов в формате emerge
  1133. """
  1134. type = "bool"
  1135. value = "off"
  1136. opt = ["-e", "--emergelist"]
  1137. def init(self):
  1138. self.label = _("Emerge-like packages list")
  1139. self.help = _("display the packages list in emerge format")
  1140. class VariableClUpdateKernelVersion(ReadonlyVariable):
  1141. """
  1142. Текущая версия ядра
  1143. """
  1144. def get(self):
  1145. return process('/bin/uname', '-r').read().strip()
  1146. class VariableClUpdateKernelSrcPath(ReadonlyVariable):
  1147. """
  1148. Каталог содержащий исходный код текущего ядра
  1149. """
  1150. def get(self):
  1151. kernel_ver = self.Get('cl_update_kernel_version')
  1152. for template_path in ("/lib/modules/%s/build",
  1153. "/usr/src/linux-%s"):
  1154. src_path = template_path % kernel_ver
  1155. if path.exists(src_path):
  1156. if path.islink(src_path):
  1157. return os.readlink(src_path)
  1158. else:
  1159. return src_path
  1160. else:
  1161. return ""
  1162. class VariableClUpdateKernelPkg(ReadonlyVariable):
  1163. """
  1164. Пакет текущего ядра
  1165. """
  1166. def get(self):
  1167. src_path = self.Get('cl_update_kernel_src_path')
  1168. if src_path:
  1169. qfile = process('/usr/bin/qfile', '-vqC', src_path)
  1170. if qfile.success():
  1171. return qfile.read().strip()
  1172. return ""
  1173. class VariableClUpdateLinesLimit(Variable):
  1174. """
  1175. Количество выводимых строк при ошибке
  1176. """
  1177. type = "int"
  1178. value = "30"
  1179. class VariableClUpdateSkipSetupSet(Variable):
  1180. """
  1181. Пропустить выполнение cl-setup-system в cl-update-profile
  1182. """
  1183. type = "bool"
  1184. value = "off"
  1185. opt = ["--skip-setup-system"]
  1186. def init(self):
  1187. self.label = _("Skip the system setup")
  1188. self.help = _("skip the system setup")
  1189. class VariableClUpdateCleanpkgSet(Variable):
  1190. """
  1191. Пропустить выполнение cl-setup-system в cl-update-profile
  1192. """
  1193. type = "bool"
  1194. value = "off"
  1195. opt = ["--clean-pkg"]
  1196. def init(self):
  1197. self.label = _("Clean obsolete programs archives")
  1198. self.help = _("clean obsolete programs archives")
  1199. class VariableClUpdateOutdatedKernelPath(Variable):
  1200. """
  1201. Файл-флаг наличия устаревшего, неудаленного ядра
  1202. """
  1203. value = "/var/lib/calculate/calculate-update/outdated_kernel"
  1204. class VariableClUpdateSkipRbSet(Variable):
  1205. """
  1206. Пропусить revdep-rebuild
  1207. """
  1208. type = "bool"
  1209. value = "off"
  1210. opt = ["-R", "--skip-revdep-rebuild"]
  1211. def init(self):
  1212. self.label = _("Skip reverse dependencies check")
  1213. self.help = _("skip reverse dependencies check")
  1214. class VariableClUpdateRevdepRebuildSet(Variable):
  1215. """
  1216. Запустить revdep-rebuild
  1217. """
  1218. type = "bool"
  1219. value = "off"
  1220. opt = ["-R", "--revdep-rebuild"]
  1221. def init(self):
  1222. self.label = _("Run reverse dependencies check")
  1223. self.help = _("run reverse dependencies check")
  1224. class VariableClUpdateOutdatedKernelSet(ReadonlyVariable):
  1225. """
  1226. Есть наличие устаревшего ядра
  1227. """
  1228. type = "bool"
  1229. def get(self):
  1230. ui = UpdateInfo(self.parent)
  1231. return "on" if ui.outdated_kernel else "off"
  1232. class VariableClUpdateBinhostList(Variable):
  1233. """
  1234. Список хостов с бинарными обновлениями
  1235. """
  1236. type = "list"
  1237. value = ["ftp://ftp.calculate-linux.ru/calculate"]
  1238. class VariableClUpdateBinhostUnstableList(Variable):
  1239. """
  1240. Список хостов с бинарными обновлениями
  1241. """
  1242. type = "list"
  1243. value = ["ftp://ftp.calculate-linux.ru/testing"]
  1244. class VariableClUpdateBinhostBase(Variable):
  1245. """
  1246. Базовый бинарный хост, используемый для установки базовых пакетов
  1247. в небинарных сборочных дистрибутивах
  1248. """
  1249. value = ""
  1250. class VariableClUpdateBinhostBaseSet(Variable):
  1251. """
  1252. Использовать или нет базовый бинарный хост
  1253. """
  1254. type = Variable.Types.Boolean
  1255. value = Variable.Off
  1256. class VariableClUpdateBinhostStableSet(Variable):
  1257. """
  1258. Удлять лишние файлы из репозиториев (например созданные пользователем)
  1259. """
  1260. type = "bool"
  1261. value = "on"
  1262. class VariableClUpdateBinhostStableOptSet(Variable):
  1263. """
  1264. Удлять лишние файлы из репозиториев (например созданные пользователем)
  1265. """
  1266. type = "bool"
  1267. value = "on"
  1268. opt = ["--stable"]
  1269. def init(self):
  1270. self.label = _("Use only stable updates")
  1271. self.help = _("use only stable updates")
  1272. def get(self):
  1273. return self.Get('cl_update_binhost_stable_set')
  1274. class VariableClUpdateBinhost(Variable):
  1275. """
  1276. Хост с бинарными обновлениями
  1277. """
  1278. value = ""
  1279. class VariableClUpdateBinhostRevisionPath(Variable):
  1280. """
  1281. Путь до revisions файлов
  1282. """
  1283. type = "list"
  1284. value = [
  1285. "grp/ini.env"
  1286. ]
  1287. class VariableClUpdateBinhostTimestampPath(Variable):
  1288. """
  1289. Путь до файла timestamp
  1290. """
  1291. value = "timestamp"
  1292. class VariableClUpdateBinhostTimeout(Variable):
  1293. """
  1294. Таймаут на проверку одного binhost
  1295. """
  1296. type = "int"
  1297. value = "5"
  1298. class VariableClUpdateCheckRepSet(Variable):
  1299. """
  1300. Удлять лишние файлы из репозиториев (например созданные пользователем)
  1301. """
  1302. type = "bool"
  1303. value = "off"
  1304. opt = ["--check-repos", "-C"]
  1305. def init(self):
  1306. self.label = _("Check the repositories integrity")
  1307. self.help = _("check and fix the repositories integrity")
  1308. class VariableClUpdateForceFixSet(Variable):
  1309. """
  1310. Удлять лишние файлы из репозиториев (например созданные пользователем)
  1311. """
  1312. type = "bool"
  1313. value = "off"
  1314. opt = ["--force-fix"]
  1315. def init(self):
  1316. self.label = _("Force fix the settings")
  1317. self.help = _("force fix the settings")
  1318. class VariableClUpdateOnedepthSet(Variable):
  1319. """
  1320. Удлять лишние файлы из репозиториев (например созданные пользователем)
  1321. """
  1322. type = "bool"
  1323. value = "off"
  1324. opt = ["--one-depth", "-1"]
  1325. def init(self):
  1326. self.label = _("Clear the history of repositories")
  1327. self.help = _("clear the history of repositories")
  1328. class VariableClUpdateEixRepositories(ReadonlyVariable):
  1329. """
  1330. Отображаемый список обновляемых репозиториев eix
  1331. """
  1332. def get(self):
  1333. return ", ".join(
  1334. x.capitalize() for x in reversed(list(chain(
  1335. self.Get('update.cl_update_rep_name'),
  1336. self.Get('update.cl_update_other_rep_name')))))
  1337. class VariableClUpdatePortageBinhost(ReadonlyVariable):
  1338. """
  1339. Прописываемый в /etc/portage/make.conf/binhost репозиторий
  1340. """
  1341. value_format = "{update.cl_update_binhost}/grp/{os_arch_machine}"
  1342. class VariableClUpdatePackageCache(ReadonlyVariable):
  1343. """
  1344. Путь кэшированного Packages
  1345. """
  1346. def get(self):
  1347. cache_path = "var/cache/edb"
  1348. chroot_path = self.Get('cl_chroot_path')
  1349. base_url = self.Get('cl_update_portage_binhost')
  1350. if not base_url:
  1351. return ""
  1352. parsed_url = urlparse(base_url)
  1353. host = parsed_url.netloc
  1354. port = parsed_url.port
  1355. user = None
  1356. passwd = None
  1357. user_passwd = ""
  1358. if "@" in host:
  1359. user, host = host.split("@", 1)
  1360. user_passwd = user + "@"
  1361. if ":" in user:
  1362. user, passwd = user.split(":", 1)
  1363. if port is not None:
  1364. port_str = ":%s" % (port,)
  1365. if host.endswith(port_str):
  1366. host = host[:-len(port_str)]
  1367. return os.path.join(chroot_path, cache_path, "binhost",
  1368. host, parsed_url.path.lstrip("/"),
  1369. "Packages")
  1370. class VariableClUpdatePackageCacheSign(ReadonlyVariable):
  1371. """
  1372. Файл с подписью Packages находящийся в кэше
  1373. """
  1374. value_format = "{update.cl_update_package_cache}.asc"
  1375. class VariableClUpdatePackageCacheSet(Variable):
  1376. """
  1377. Необходимость обновить Packages
  1378. """
  1379. type = "bool"
  1380. def get(self):
  1381. packages_fn = self.Get('cl_update_package_cache')
  1382. gpg = self.Get('cl_update_gpg')
  1383. packages_asc_fn = self.Get('cl_update_package_cache_sign')
  1384. if (not path.exists(packages_fn) or
  1385. gpg and not path.exists(packages_asc_fn)):
  1386. return "on"
  1387. pi = PackagesIndex(readFile(packages_fn))
  1388. try:
  1389. ttl = int(pi.get("TTL", "0"))
  1390. if ttl > HOURS:
  1391. return "off"
  1392. except ValueError:
  1393. return "on"
  1394. return "on"
  1395. class VariableClUpdateWithBdepsSet(Variable):
  1396. """
  1397. Добавление --with-bdeps при вызове emerge
  1398. """
  1399. type = Variable.Types.Tristate
  1400. value = Variable.Auto
  1401. class VariableClUpdateWithBdepsOptSet(Variable):
  1402. """
  1403. Добавление --with-bdeps при вызове emerge (опция)
  1404. """
  1405. type = Variable.Types.Tristate
  1406. opt = ["--with-bdeps"]
  1407. metavalue = "ON/OFF/AUTO"
  1408. def init(self):
  1409. self.help = _("save packages used during build")
  1410. self.label = _("Save packages used during build")
  1411. def get(self):
  1412. return self.Get('cl_update_with_bdeps_set')
  1413. class VariableClUpdateForceDepcleanSet(Variable):
  1414. """
  1415. Принудительный вызов depclean
  1416. """
  1417. type = Variable.Types.Boolean
  1418. value = Variable.Off
  1419. class VariableClUpdateUsetagSet(Variable):
  1420. """
  1421. Использовать тэги при синхронизации репозиториев
  1422. """
  1423. type = Variable.Types.Boolean
  1424. value = Variable.On
  1425. class VariableClUpdateSshkeyPath(Variable):
  1426. """
  1427. Путь до ssh ключа
  1428. """
  1429. value = "/var/lib/calculate/id_rsa"
  1430. class VariableClUpdateBadSignSet(Variable):
  1431. """
  1432. Ошибка проверки подписи Packages
  1433. """
  1434. type = Variable.Types.Boolean
  1435. value = Variable.Off
  1436. class VariableClUpdateGpgKeys(Variable):
  1437. """
  1438. Список ключей для проверки подписи Packages
  1439. """
  1440. type = Variable.Types.List
  1441. value = ["/usr/share/openpgp-keys/calculate-release.asc"]
  1442. class VariableClUpdateGpg(ReadonlyVariable):
  1443. """
  1444. Объект проверки подписи
  1445. """
  1446. type = Variable.Types.Object
  1447. value = ""
  1448. def close(self):
  1449. val = self.Get()
  1450. if val:
  1451. val.close()
  1452. class VariableClUpdateUseDowngradeSet(ReadonlyVariable):
  1453. """
  1454. Можно использовать downgrade binhost
  1455. """
  1456. type = Variable.Types.Boolean
  1457. def get(self):
  1458. """
  1459. Выполняется переход с unstable ветки на stable
  1460. """
  1461. return (self.GetBool("cl_update_binhost_stable_opt_set") and
  1462. not self.GetBool("cl_update_binhost_stable_opt_set"))
  1463. class VariableClUpdatePortageBinhostPath(Variable):
  1464. """
  1465. Файл в котором хранится параметр portage PORTAGE_BINHOST
  1466. """
  1467. value = "/etc/portage/make.conf/binhost"