cmd.go 16 KB

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