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.

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