cmd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. var cmdArgs = makeArguments()
  15. func usage() {
  16. fmt.Println(`Usage:
  17. yay <operation> [...]
  18. yay <package(s)>
  19. operations:
  20. yay {-h --help}
  21. yay {-V --version}
  22. yay {-D --database} <options> <package(s)>
  23. yay {-F --files} [options] [package(s)]
  24. yay {-Q --query} [options] [package(s)]
  25. yay {-R --remove} [options] <package(s)>
  26. yay {-S --sync} [options] [package(s)]
  27. yay {-T --deptest} [options] [package(s)]
  28. yay {-U --upgrade} [options] <file(s)>
  29. New operations:
  30. yay {-Y --yay} [options] [package(s)]
  31. yay {-P --print} [options]
  32. yay {-G --getpkgbuild} [package(s)]
  33. Permanent configuration options:
  34. --save Causes the following options to be saved back to the
  35. config file when used
  36. --builddir <dir> Directory to use for building AUR Packages
  37. --editor <file> Editor to use when editing PKGBUILDs
  38. --makepkg <file> makepkg command to use
  39. --pacman <file> pacman command to use
  40. --tar <file> bsdtar command to use
  41. --git <file> git command to use
  42. --gpg <file> gpg command to use
  43. --config <file> pacman.conf file to use
  44. --requestsplitn <n> Max amount of packages to query per AUR request
  45. --topdown Shows repository's packages first and then AUR's
  46. --bottomup Shows AUR's packages first and then repository's
  47. --devel Check development packages during sysupgrade
  48. --nodevel Do not check development packages
  49. --afterclean Remove package sources after successful install
  50. --noafterclean Do not remove package sources after successful build
  51. --timeupdate Check package's AUR page for changes during sysupgrade
  52. --notimeupdate Do not checking of AUR page changes
  53. --redownload Always download pkgbuilds of targets
  54. --redownloadall Always download pkgbuilds of all AUR packages
  55. --noredownload Skip pkgbuild download if in cache and up to date
  56. --rebuild Always build target packages
  57. --rebuildall Always build all AUR packages
  58. --rebuildtree Always build all AUR packages even if installed
  59. --norebuild Skip package build if in cache and up to date
  60. --mflags <flags> Pass arguments to makepkg
  61. --gpgflags <flags> Pass arguments to gpg
  62. --sudoloop Loop sudo calls in the background to avoid timeout
  63. --nosudoloop Do not loop sudo calls in the background
  64. Print specific options:
  65. -c --complete Used for completions
  66. -d --defaultconfig Print default yay configuration
  67. -g --config Print current yay configuration
  68. -n --numberupgrades Print number of updates
  69. -s --stats Display system package statistics
  70. -u --upgrades Print update list
  71. Yay specific options:
  72. -c --clean Remove unneeded dependencies
  73. --gendb Generates development package DB used for updating
  74. If no operation is provided -Y will be assumed`)
  75. }
  76. func initPaths() {
  77. if configHome = os.Getenv("XDG_CONFIG_HOME"); configHome != "" {
  78. if info, err := os.Stat(configHome); err == nil && info.IsDir() {
  79. configHome = configHome + "/yay"
  80. } else {
  81. configHome = os.Getenv("HOME") + "/.config/yay"
  82. }
  83. } else {
  84. configHome = os.Getenv("HOME") + "/.config/yay"
  85. }
  86. if cacheHome = os.Getenv("XDG_CACHE_HOME"); cacheHome != "" {
  87. if info, err := os.Stat(cacheHome); err == nil && info.IsDir() {
  88. cacheHome = cacheHome + "/yay"
  89. } else {
  90. cacheHome = os.Getenv("HOME") + "/.cache/yay"
  91. }
  92. } else {
  93. cacheHome = os.Getenv("HOME") + "/.cache/yay"
  94. }
  95. configFile = configHome + "/" + configFileName
  96. vcsFile = cacheHome + "/" + vcsFileName
  97. completionFile = cacheHome + "/" + completionFilePrefix
  98. }
  99. func initConfig() (err error) {
  100. defaultSettings(&config)
  101. if _, err = os.Stat(configFile); os.IsNotExist(err) {
  102. err = os.MkdirAll(filepath.Dir(configFile), 0755)
  103. if err != nil {
  104. err = fmt.Errorf("Unable to create config directory:\n%s\n"+
  105. "The error was:\n%s", filepath.Dir(configFile), err)
  106. return
  107. }
  108. // Save the default config if nothing is found
  109. config.saveConfig()
  110. } else {
  111. cfile, errf := os.OpenFile(configFile, os.O_RDWR|os.O_CREATE, 0644)
  112. if errf != nil {
  113. fmt.Printf("Error reading config: %s\n", err)
  114. } else {
  115. defer cfile.Close()
  116. decoder := json.NewDecoder(cfile)
  117. err = decoder.Decode(&config)
  118. if err != nil {
  119. fmt.Println("Loading default Settings.\nError reading config:",
  120. err)
  121. defaultSettings(&config)
  122. }
  123. }
  124. }
  125. return
  126. }
  127. func initVCS() (err error) {
  128. if _, err = os.Stat(vcsFile); os.IsNotExist(err) {
  129. err = os.MkdirAll(filepath.Dir(vcsFile), 0755)
  130. if err != nil {
  131. err = fmt.Errorf("Unable to create vcs directory:\n%s\n"+
  132. "The error was:\n%s", filepath.Dir(configFile), err)
  133. return
  134. }
  135. } else {
  136. vfile, err := os.OpenFile(vcsFile, os.O_RDONLY|os.O_CREATE, 0644)
  137. if err == nil {
  138. defer vfile.Close()
  139. decoder := json.NewDecoder(vfile)
  140. _ = decoder.Decode(&savedInfo)
  141. }
  142. }
  143. return
  144. }
  145. func initAlpm() (err error) {
  146. var value string
  147. var exists bool
  148. //var double bool
  149. value, _, exists = cmdArgs.getArg("config")
  150. if exists {
  151. config.PacmanConf = value
  152. }
  153. alpmConf, err = readAlpmConfig(config.PacmanConf)
  154. if err != nil {
  155. err = fmt.Errorf("Unable to read Pacman conf: %s", err)
  156. return
  157. }
  158. value, _, exists = cmdArgs.getArg("dbpath", "b")
  159. if exists {
  160. alpmConf.DBPath = value
  161. }
  162. value, _, exists = cmdArgs.getArg("root", "r")
  163. if exists {
  164. alpmConf.RootDir = value
  165. }
  166. value, _, exists = cmdArgs.getArg("arch")
  167. if exists {
  168. alpmConf.Architecture = value
  169. }
  170. value, _, exists = cmdArgs.getArg("ignore")
  171. if exists {
  172. alpmConf.IgnorePkg = append(alpmConf.IgnorePkg, strings.Split(value, ",")...)
  173. }
  174. value, _, exists = cmdArgs.getArg("ignoregroup")
  175. if exists {
  176. alpmConf.IgnoreGroup = append(alpmConf.IgnoreGroup, strings.Split(value, ",")...)
  177. }
  178. //TODO
  179. //current system does not allow duplicate arguments
  180. //but pacman allows multiple cachdirs to be passed
  181. //for now only handle one cache dir
  182. value, _, exists = cmdArgs.getArg("cachdir")
  183. if exists {
  184. alpmConf.CacheDir = []string{value}
  185. }
  186. value, _, exists = cmdArgs.getArg("gpgdir")
  187. if exists {
  188. alpmConf.GPGDir = value
  189. }
  190. alpmHandle, err = alpmConf.CreateHandle()
  191. if err != nil {
  192. err = fmt.Errorf("Unable to CreateHandle: %s", err)
  193. return
  194. }
  195. alpmHandle.SetQuestionCallback(questionCallback)
  196. return
  197. }
  198. func main() {
  199. var status int
  200. var err error
  201. if 0 == os.Geteuid() {
  202. fmt.Println("Please avoid running yay as root/sudo.")
  203. }
  204. err = cmdArgs.parseCommandLine()
  205. if err != nil {
  206. fmt.Println(err)
  207. status = 1
  208. goto cleanup
  209. }
  210. initPaths()
  211. err = initConfig()
  212. if err != nil {
  213. fmt.Println(err)
  214. status = 1
  215. goto cleanup
  216. }
  217. err = initVCS()
  218. if err != nil {
  219. fmt.Println(err)
  220. status = 1
  221. goto cleanup
  222. }
  223. err = initAlpm()
  224. if err != nil {
  225. fmt.Println(err)
  226. status = 1
  227. goto cleanup
  228. }
  229. err = handleCmd()
  230. if err != nil {
  231. fmt.Println(err)
  232. status = 1
  233. goto cleanup
  234. }
  235. cleanup:
  236. //cleanup
  237. //from here on out dont exit if an error occurs
  238. //if we fail to save the configuration
  239. //at least continue on and try clean up other parts
  240. if alpmHandle != nil {
  241. err = alpmHandle.Release()
  242. if err != nil {
  243. fmt.Println(err)
  244. status = 1
  245. }
  246. }
  247. os.Exit(status)
  248. }
  249. func sudoLoopBackground() {
  250. updateSudo()
  251. go sudoLoop()
  252. }
  253. func sudoLoop() {
  254. for {
  255. updateSudo()
  256. time.Sleep(298 * time.Second)
  257. }
  258. }
  259. func updateSudo() {
  260. for {
  261. cmd := exec.Command("sudo", "-v")
  262. cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
  263. err := cmd.Run()
  264. if err != nil {
  265. fmt.Println(err)
  266. } else {
  267. break
  268. }
  269. }
  270. }
  271. func handleCmd() (err error) {
  272. for option, value := range cmdArgs.options {
  273. if handleConfig(option, value) {
  274. cmdArgs.delArg(option)
  275. }
  276. }
  277. for option, value := range cmdArgs.globals {
  278. if handleConfig(option, value) {
  279. cmdArgs.delArg(option)
  280. }
  281. }
  282. if shouldSaveConfig {
  283. config.saveConfig()
  284. }
  285. if config.SudoLoop && cmdArgs.needRoot() {
  286. sudoLoopBackground()
  287. }
  288. switch cmdArgs.op {
  289. case "V", "version":
  290. handleVersion()
  291. case "D", "database":
  292. err = passToPacman(cmdArgs)
  293. case "F", "files":
  294. err = passToPacman(cmdArgs)
  295. case "Q", "query":
  296. err = handleQuery()
  297. case "R", "remove":
  298. err = handleRemove()
  299. case "S", "sync":
  300. err = handleSync()
  301. case "T", "deptest":
  302. err = passToPacman(cmdArgs)
  303. case "U", "upgrade":
  304. err =passToPacman(cmdArgs)
  305. case "G", "getpkgbuild":
  306. err = handleGetpkgbuild()
  307. case "P", "print":
  308. err = handlePrint()
  309. case "Y", "--yay":
  310. err = handleYay()
  311. default:
  312. //this means we allowed an op but not implement it
  313. //if this happens it an error in the code and not the usage
  314. err = fmt.Errorf("unhandled operation")
  315. }
  316. return
  317. }
  318. func handleQuery() error {
  319. var err error
  320. if cmdArgs.existsArg("u", "upgrades") {
  321. err = printUpdateList(cmdArgs)
  322. } else {
  323. err = passToPacman(cmdArgs)
  324. }
  325. return err
  326. }
  327. //this function should only set config options
  328. //but currently still uses the switch left over from old code
  329. //eventually this should be refactored out futher
  330. //my current plan is to have yay specific operations in its own operator
  331. //e.g. yay -Y --gendb
  332. //e.g yay -Yg
  333. func handleConfig(option, value string) bool {
  334. switch option {
  335. case "save":
  336. shouldSaveConfig = true
  337. case "afterclean":
  338. config.CleanAfter = true
  339. case "noafterclean":
  340. config.CleanAfter = false
  341. case "devel":
  342. config.Devel = true
  343. case "nodevel":
  344. config.Devel = false
  345. case "timeupdate":
  346. config.TimeUpdate = true
  347. case "notimeupdate":
  348. config.TimeUpdate = false
  349. case "topdown":
  350. config.SortMode = TopDown
  351. case "bottomup":
  352. config.SortMode = BottomUp
  353. case "noconfirm":
  354. config.NoConfirm = true
  355. case "redownload":
  356. config.ReDownload = "yes"
  357. case "redownloadall":
  358. config.ReDownload = "all"
  359. case "noredownload":
  360. config.ReDownload = "no"
  361. case "rebuild":
  362. config.ReBuild = "yes"
  363. case "rebuildall":
  364. config.ReBuild = "all"
  365. case "rebuildtree":
  366. config.ReBuild = "tree"
  367. case "norebuild":
  368. config.ReBuild = "no"
  369. case "gpgflags":
  370. config.GpgFlags = value
  371. case "mflags":
  372. config.MFlags = value
  373. case "builddir":
  374. config.BuildDir = value
  375. case "editor":
  376. config.Editor = value
  377. case "makepkg":
  378. config.MakepkgBin = value
  379. case "pacman":
  380. config.PacmanBin = value
  381. case "tar":
  382. config.TarBin = value
  383. case "git":
  384. config.GitBin = value
  385. case "gpg":
  386. config.GpgBin = value
  387. case "requestsplitn":
  388. n, err := strconv.Atoi(value)
  389. if err == nil && n > 0 {
  390. config.RequestSplitN = n
  391. }
  392. case "sudoloop":
  393. config.SudoLoop = true
  394. case "nosudoloop":
  395. config.SudoLoop = false
  396. default:
  397. return false
  398. }
  399. return true
  400. }
  401. func handleVersion() {
  402. fmt.Printf("yay v%s\n", version)
  403. }
  404. func handlePrint() (err error) {
  405. switch {
  406. case cmdArgs.existsArg("d", "defaultconfig"):
  407. var tmpConfig Configuration
  408. defaultSettings(&tmpConfig)
  409. fmt.Printf("%v", tmpConfig)
  410. case cmdArgs.existsArg("g", "config"):
  411. fmt.Printf("%v", config)
  412. case cmdArgs.existsArg("n", "numberupgrades"):
  413. err = printNumberOfUpdates()
  414. case cmdArgs.existsArg("u", "upgrades"):
  415. err = printUpdateList(cmdArgs)
  416. case cmdArgs.existsArg("c", "complete"):
  417. switch {
  418. case cmdArgs.existsArg("f", "fish"):
  419. complete("fish")
  420. default:
  421. complete("sh")
  422. }
  423. case cmdArgs.existsArg("s", "stats"):
  424. err = localStatistics()
  425. default:
  426. err = nil
  427. }
  428. return err
  429. }
  430. func handleYay() (err error) {
  431. //_, options, targets := cmdArgs.formatArgs()
  432. if cmdArgs.existsArg("h", "help") {
  433. usage()
  434. } else if cmdArgs.existsArg("gendb") {
  435. err = createDevelDB()
  436. if err != nil {
  437. return
  438. }
  439. } else if cmdArgs.existsArg("c", "clean") {
  440. err = cleanDependencies()
  441. } else if len(cmdArgs.targets) > 0 {
  442. err = handleYogurt()
  443. }
  444. return
  445. }
  446. func handleGetpkgbuild() (err error) {
  447. err = getPkgbuilds(cmdArgs.formatTargets())
  448. return
  449. }
  450. func handleYogurt() (err error) {
  451. options := cmdArgs.formatArgs()
  452. targets := cmdArgs.formatTargets()
  453. config.SearchMode = NumberMenu
  454. err = numberMenu(targets, options)
  455. return
  456. }
  457. func handleSync() (err error) {
  458. targets := cmdArgs.formatTargets()
  459. if cmdArgs.existsArg("y", "refresh") {
  460. arguments := cmdArgs.copy()
  461. cmdArgs.delArg("y", "refresh")
  462. arguments.delArg("u", "sysupgrade")
  463. arguments.delArg("s", "search")
  464. arguments.delArg("i", "info")
  465. arguments.delArg("l", "list")
  466. arguments.targets = make(stringSet)
  467. err = passToPacman(arguments)
  468. if err != nil {
  469. return
  470. }
  471. }
  472. if cmdArgs.existsArg("s", "search") {
  473. if cmdArgs.existsArg("q", "quiet") {
  474. config.SearchMode = Minimal
  475. } else {
  476. config.SearchMode = Detailed
  477. }
  478. err = syncSearch(targets)
  479. } else if cmdArgs.existsArg("l", "list") {
  480. err = passToPacman(cmdArgs)
  481. } else if cmdArgs.existsArg("c", "clean") {
  482. err = passToPacman(cmdArgs)
  483. } else if cmdArgs.existsArg("i", "info") {
  484. err = syncInfo(targets)
  485. } else if cmdArgs.existsArg("u", "sysupgrade") {
  486. err = install(cmdArgs)
  487. } else if len(cmdArgs.targets) > 0 {
  488. err = install(cmdArgs)
  489. }
  490. return
  491. }
  492. func handleRemove() (err error) {
  493. removeVCSPackage(cmdArgs.formatTargets())
  494. err = passToPacman(cmdArgs)
  495. return
  496. }
  497. // NumberMenu presents a CLI for selecting packages to install.
  498. func numberMenu(pkgS []string, flags []string) (err error) {
  499. aurQ, err := narrowSearch(pkgS, true)
  500. if err != nil {
  501. fmt.Println("Error during AUR search:", err)
  502. }
  503. numaq := len(aurQ)
  504. repoQ, numpq, err := queryRepo(pkgS)
  505. if err != nil {
  506. return
  507. }
  508. if numpq == 0 && numaq == 0 {
  509. return fmt.Errorf("no packages match search")
  510. }
  511. if config.SortMode == BottomUp {
  512. aurQ.printSearch(numpq + 1)
  513. repoQ.printSearch()
  514. } else {
  515. repoQ.printSearch()
  516. aurQ.printSearch(numpq + 1)
  517. }
  518. fmt.Println(bold(green(arrow + " Packages to install (eg: 1 2 3, 1-3 or ^4)")))
  519. fmt.Print(bold(green(arrow + " ")))
  520. reader := bufio.NewReader(os.Stdin)
  521. numberBuf, overflow, err := reader.ReadLine()
  522. if err != nil {
  523. return err
  524. }
  525. if overflow {
  526. return fmt.Errorf("Input too long")
  527. }
  528. include, exclude, _, otherExclude := parseNumberMenu(string(numberBuf))
  529. arguments := makeArguments()
  530. isInclude := len(exclude) == 0 && len(otherExclude) == 0
  531. for i, pkg := range repoQ {
  532. target := len(repoQ) - i
  533. if config.SortMode == TopDown {
  534. target = i + 1
  535. }
  536. if isInclude && include.get(target) {
  537. arguments.addTarget(pkg.DB().Name() + "/" + pkg.Name())
  538. }
  539. if !isInclude && !exclude.get(target) {
  540. arguments.addTarget(pkg.DB().Name() + "/" + pkg.Name())
  541. }
  542. }
  543. for i, pkg := range aurQ {
  544. target := len(aurQ) - i + len(repoQ)
  545. if config.SortMode == TopDown {
  546. target = i + 1 + len(repoQ)
  547. }
  548. if isInclude && include.get(target) {
  549. arguments.addTarget("aur/" + pkg.Name)
  550. }
  551. if !isInclude && !exclude.get(target) {
  552. arguments.addTarget("aur/" + pkg.Name)
  553. }
  554. }
  555. if config.SudoLoop {
  556. sudoLoopBackground()
  557. }
  558. err = install(arguments)
  559. return err
  560. }
  561. // passToPacman outsources execution to pacman binary without modifications.
  562. func passToPacman(args *arguments) error {
  563. var cmd *exec.Cmd
  564. argArr := make([]string, 0)
  565. if args.needRoot() {
  566. argArr = append(argArr, "sudo")
  567. }
  568. argArr = append(argArr, config.PacmanBin)
  569. argArr = append(argArr, cmdArgs.formatGlobals()...)
  570. argArr = append(argArr, args.formatArgs()...)
  571. if config.NoConfirm {
  572. argArr = append(argArr, "--noconfirm")
  573. }
  574. argArr = append(argArr, "--")
  575. argArr = append(argArr, args.formatTargets()...)
  576. cmd = exec.Command(argArr[0], argArr[1:]...)
  577. cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
  578. err := cmd.Run()
  579. return err
  580. }
  581. //passToPacman but return the output instead of showing the user
  582. func passToPacmanCapture(args *arguments) (string, string, error) {
  583. var outbuf, errbuf bytes.Buffer
  584. var cmd *exec.Cmd
  585. argArr := make([]string, 0)
  586. if args.needRoot() {
  587. argArr = append(argArr, "sudo")
  588. }
  589. argArr = append(argArr, config.PacmanBin)
  590. argArr = append(argArr, cmdArgs.formatGlobals()...)
  591. argArr = append(argArr, args.formatArgs()...)
  592. if config.NoConfirm {
  593. argArr = append(argArr, "--noconfirm")
  594. }
  595. argArr = append(argArr, "--")
  596. argArr = append(argArr, args.formatTargets()...)
  597. cmd = exec.Command(argArr[0], argArr[1:]...)
  598. cmd.Stdout = &outbuf
  599. cmd.Stderr = &errbuf
  600. err := cmd.Run()
  601. stdout := outbuf.String()
  602. stderr := errbuf.String()
  603. return stdout, stderr, err
  604. }
  605. // passToMakepkg outsources execution to makepkg binary without modifications.
  606. func passToMakepkg(dir string, args ...string) (err error) {
  607. if config.NoConfirm {
  608. args = append(args)
  609. }
  610. mflags := strings.Fields(config.MFlags)
  611. args = append(args, mflags...)
  612. cmd := exec.Command(config.MakepkgBin, args...)
  613. cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
  614. cmd.Dir = dir
  615. err = cmd.Run()
  616. if err == nil {
  617. _ = saveVCSInfo()
  618. }
  619. return
  620. }