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.

119 lines
2.4 KiB

  1. // +build ignore
  2. package main
  3. import (
  4. "archive/tar"
  5. "compress/gzip"
  6. "flag"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "os"
  13. "path"
  14. "path/filepath"
  15. "strings"
  16. "code.gitea.io/gitea/modules/util"
  17. )
  18. func main() {
  19. var (
  20. prefix = "gitea-gitignore"
  21. url = "https://api.github.com/repos/github/gitignore/tarball"
  22. destination = ""
  23. )
  24. flag.StringVar(&destination, "dest", "options/gitignore/", "destination for the gitignores")
  25. flag.Parse()
  26. file, err := ioutil.TempFile(os.TempDir(), prefix)
  27. if err != nil {
  28. log.Fatalf("Failed to create temp file. %s", err)
  29. }
  30. defer util.Remove(file.Name())
  31. resp, err := http.Get(url)
  32. if err != nil {
  33. log.Fatalf("Failed to download archive. %s", err)
  34. }
  35. defer resp.Body.Close()
  36. if _, err := io.Copy(file, resp.Body); err != nil {
  37. log.Fatalf("Failed to copy archive to file. %s", err)
  38. }
  39. if _, err := file.Seek(0, 0); err != nil {
  40. log.Fatalf("Failed to reset seek on archive. %s", err)
  41. }
  42. gz, err := gzip.NewReader(file)
  43. if err != nil {
  44. log.Fatalf("Failed to gunzip the archive. %s", err)
  45. }
  46. tr := tar.NewReader(gz)
  47. filesToCopy := make(map[string]string, 0)
  48. for {
  49. hdr, err := tr.Next()
  50. if err == io.EOF {
  51. break
  52. }
  53. if err != nil {
  54. log.Fatalf("Failed to iterate archive. %s", err)
  55. }
  56. if filepath.Ext(hdr.Name) != ".gitignore" {
  57. continue
  58. }
  59. if hdr.Typeflag == tar.TypeSymlink {
  60. fmt.Printf("Found symlink %s -> %s\n", hdr.Name, hdr.Linkname)
  61. filesToCopy[strings.TrimSuffix(filepath.Base(hdr.Name), ".gitignore")] = strings.TrimSuffix(filepath.Base(hdr.Linkname), ".gitignore")
  62. continue
  63. }
  64. out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".gitignore")))
  65. if err != nil {
  66. log.Fatalf("Failed to create new file. %s", err)
  67. }
  68. defer out.Close()
  69. if _, err := io.Copy(out, tr); err != nil {
  70. log.Fatalf("Failed to write new file. %s", err)
  71. } else {
  72. fmt.Printf("Written %s\n", out.Name())
  73. }
  74. }
  75. for dst, src := range filesToCopy {
  76. // Read all content of src to data
  77. src = path.Join(destination, src)
  78. data, err := ioutil.ReadFile(src)
  79. if err != nil {
  80. log.Fatalf("Failed to read src file. %s", err)
  81. }
  82. // Write data to dst
  83. dst = path.Join(destination, dst)
  84. err = ioutil.WriteFile(dst, data, 0644)
  85. if err != nil {
  86. log.Fatalf("Failed to write new file. %s", err)
  87. }
  88. fmt.Printf("Written (copy of %s) %s\n", src, dst)
  89. }
  90. fmt.Println("Done")
  91. }