update-license.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // +build none
  17. /*
  18. This command generates GPL license headers on top of all source files.
  19. You can run it once per month, before cutting a release or just
  20. whenever you feel like it.
  21. go run update-license.go
  22. All authors (people who have contributed code) are listed in the
  23. AUTHORS file. The author names are mapped and deduplicated using the
  24. .mailmap file. You can use .mailmap to set the canonical name and
  25. address for each author. See git-shortlog(1) for an explanation of the
  26. .mailmap format.
  27. Please review the resulting diff to check whether the correct
  28. copyright assignments are performed.
  29. */
  30. package main
  31. import (
  32. "bufio"
  33. "bytes"
  34. "fmt"
  35. "io/ioutil"
  36. "log"
  37. "os"
  38. "os/exec"
  39. "path/filepath"
  40. "regexp"
  41. "runtime"
  42. "sort"
  43. "strconv"
  44. "strings"
  45. "sync"
  46. "text/template"
  47. "time"
  48. )
  49. var (
  50. // only files with these extensions will be considered
  51. extensions = []string{".go", ".js", ".qml"}
  52. // paths with any of these prefixes will be skipped
  53. skipPrefixes = []string{
  54. // boring stuff
  55. "vendor/", "tests/testdata/", "build/",
  56. // don't relicense vendored sources
  57. "cmd/internal/browser",
  58. "consensus/ethash/xor.go",
  59. "crypto/bn256/",
  60. "crypto/ecies/",
  61. "crypto/secp256k1/curve.go",
  62. "crypto/sha3/",
  63. "internal/jsre/deps",
  64. "log/",
  65. "common/bitutil/bitutil",
  66. }
  67. // paths with this prefix are licensed as GPL. all other files are LGPL.
  68. gplPrefixes = []string{"cmd/"}
  69. // this regexp must match the entire license comment at the
  70. // beginning of each file.
  71. licenseCommentRE = regexp.MustCompile(`^//\s*(Copyright|This file is part of).*?\n(?://.*?\n)*\n*`)
  72. // this text appears at the start of AUTHORS
  73. authorsFileHeader = "# This is the official list of go-ethereum authors for copyright purposes.\n\n"
  74. )
  75. // this template generates the license comment.
  76. // its input is an info structure.
  77. var licenseT = template.Must(template.New("").Parse(`
  78. // Copyright {{.Year}} The go-ethereum Authors
  79. // This file is part of {{.Whole false}}.
  80. //
  81. // {{.Whole true}} is free software: you can redistribute it and/or modify
  82. // it under the terms of the GNU {{.License}} as published by
  83. // the Free Software Foundation, either version 3 of the License, or
  84. // (at your option) any later version.
  85. //
  86. // {{.Whole true}} is distributed in the hope that it will be useful,
  87. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  88. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  89. // GNU {{.License}} for more details.
  90. //
  91. // You should have received a copy of the GNU {{.License}}
  92. // along with {{.Whole false}}. If not, see <http://www.gnu.org/licenses/>.
  93. `[1:]))
  94. type info struct {
  95. file string
  96. Year int64
  97. }
  98. func (i info) License() string {
  99. if i.gpl() {
  100. return "General Public License"
  101. }
  102. return "Lesser General Public License"
  103. }
  104. func (i info) ShortLicense() string {
  105. if i.gpl() {
  106. return "GPL"
  107. }
  108. return "LGPL"
  109. }
  110. func (i info) Whole(startOfSentence bool) string {
  111. if i.gpl() {
  112. return "go-ethereum"
  113. }
  114. if startOfSentence {
  115. return "The go-ethereum library"
  116. }
  117. return "the go-ethereum library"
  118. }
  119. func (i info) gpl() bool {
  120. for _, p := range gplPrefixes {
  121. if strings.HasPrefix(i.file, p) {
  122. return true
  123. }
  124. }
  125. return false
  126. }
  127. func main() {
  128. var (
  129. files = getFiles()
  130. filec = make(chan string)
  131. infoc = make(chan *info, 20)
  132. wg sync.WaitGroup
  133. )
  134. writeAuthors(files)
  135. go func() {
  136. for _, f := range files {
  137. filec <- f
  138. }
  139. close(filec)
  140. }()
  141. for i := runtime.NumCPU(); i >= 0; i-- {
  142. // getting file info is slow and needs to be parallel.
  143. // it traverses git history for each file.
  144. wg.Add(1)
  145. go getInfo(filec, infoc, &wg)
  146. }
  147. go func() {
  148. wg.Wait()
  149. close(infoc)
  150. }()
  151. writeLicenses(infoc)
  152. }
  153. func skipFile(path string) bool {
  154. if strings.Contains(path, "/testdata/") {
  155. return true
  156. }
  157. for _, p := range skipPrefixes {
  158. if strings.HasPrefix(path, p) {
  159. return true
  160. }
  161. }
  162. return false
  163. }
  164. func getFiles() []string {
  165. cmd := exec.Command("git", "ls-tree", "-r", "--name-only", "HEAD")
  166. var files []string
  167. err := doLines(cmd, func(line string) {
  168. if skipFile(line) {
  169. return
  170. }
  171. ext := filepath.Ext(line)
  172. for _, wantExt := range extensions {
  173. if ext == wantExt {
  174. goto keep
  175. }
  176. }
  177. return
  178. keep:
  179. files = append(files, line)
  180. })
  181. if err != nil {
  182. log.Fatal("error getting files:", err)
  183. }
  184. return files
  185. }
  186. var authorRegexp = regexp.MustCompile(`\s*[0-9]+\s*(.*)`)
  187. func gitAuthors(files []string) []string {
  188. cmds := []string{"shortlog", "-s", "-n", "-e", "HEAD", "--"}
  189. cmds = append(cmds, files...)
  190. cmd := exec.Command("git", cmds...)
  191. var authors []string
  192. err := doLines(cmd, func(line string) {
  193. m := authorRegexp.FindStringSubmatch(line)
  194. if len(m) > 1 {
  195. authors = append(authors, m[1])
  196. }
  197. })
  198. if err != nil {
  199. log.Fatalln("error getting authors:", err)
  200. }
  201. return authors
  202. }
  203. func readAuthors() []string {
  204. content, err := ioutil.ReadFile("AUTHORS")
  205. if err != nil && !os.IsNotExist(err) {
  206. log.Fatalln("error reading AUTHORS:", err)
  207. }
  208. var authors []string
  209. for _, a := range bytes.Split(content, []byte("\n")) {
  210. if len(a) > 0 && a[0] != '#' {
  211. authors = append(authors, string(a))
  212. }
  213. }
  214. // Retranslate existing authors through .mailmap.
  215. // This should catch email address changes.
  216. authors = mailmapLookup(authors)
  217. return authors
  218. }
  219. func mailmapLookup(authors []string) []string {
  220. if len(authors) == 0 {
  221. return nil
  222. }
  223. cmds := []string{"check-mailmap", "--"}
  224. cmds = append(cmds, authors...)
  225. cmd := exec.Command("git", cmds...)
  226. var translated []string
  227. err := doLines(cmd, func(line string) {
  228. translated = append(translated, line)
  229. })
  230. if err != nil {
  231. log.Fatalln("error translating authors:", err)
  232. }
  233. return translated
  234. }
  235. func writeAuthors(files []string) {
  236. merge := make(map[string]bool)
  237. // Add authors that Git reports as contributorxs.
  238. // This is the primary source of author information.
  239. for _, a := range gitAuthors(files) {
  240. merge[a] = true
  241. }
  242. // Add existing authors from the file. This should ensure that we
  243. // never lose authors, even if Git stops listing them. We can also
  244. // add authors manually this way.
  245. for _, a := range readAuthors() {
  246. merge[a] = true
  247. }
  248. // Write sorted list of authors back to the file.
  249. var result []string
  250. for a := range merge {
  251. result = append(result, a)
  252. }
  253. sort.Strings(result)
  254. content := new(bytes.Buffer)
  255. content.WriteString(authorsFileHeader)
  256. for _, a := range result {
  257. content.WriteString(a)
  258. content.WriteString("\n")
  259. }
  260. fmt.Println("writing AUTHORS")
  261. if err := ioutil.WriteFile("AUTHORS", content.Bytes(), 0644); err != nil {
  262. log.Fatalln(err)
  263. }
  264. }
  265. func getInfo(files <-chan string, out chan<- *info, wg *sync.WaitGroup) {
  266. for file := range files {
  267. stat, err := os.Lstat(file)
  268. if err != nil {
  269. fmt.Printf("ERROR %s: %v\n", file, err)
  270. continue
  271. }
  272. if !stat.Mode().IsRegular() {
  273. continue
  274. }
  275. if isGenerated(file) {
  276. continue
  277. }
  278. info, err := fileInfo(file)
  279. if err != nil {
  280. fmt.Printf("ERROR %s: %v\n", file, err)
  281. continue
  282. }
  283. out <- info
  284. }
  285. wg.Done()
  286. }
  287. func isGenerated(file string) bool {
  288. fd, err := os.Open(file)
  289. if err != nil {
  290. return false
  291. }
  292. defer fd.Close()
  293. buf := make([]byte, 2048)
  294. n, _ := fd.Read(buf)
  295. buf = buf[:n]
  296. for _, l := range bytes.Split(buf, []byte("\n")) {
  297. if bytes.HasPrefix(l, []byte("// Code generated")) {
  298. return true
  299. }
  300. }
  301. return false
  302. }
  303. // fileInfo finds the lowest year in which the given file was committed.
  304. func fileInfo(file string) (*info, error) {
  305. info := &info{file: file, Year: int64(time.Now().Year())}
  306. cmd := exec.Command("git", "log", "--follow", "--find-renames=80", "--find-copies=80", "--pretty=format:%ai", "--", file)
  307. err := doLines(cmd, func(line string) {
  308. y, err := strconv.ParseInt(line[:4], 10, 64)
  309. if err != nil {
  310. fmt.Printf("cannot parse year: %q", line[:4])
  311. }
  312. if y < info.Year {
  313. info.Year = y
  314. }
  315. })
  316. return info, err
  317. }
  318. func writeLicenses(infos <-chan *info) {
  319. for i := range infos {
  320. writeLicense(i)
  321. }
  322. }
  323. func writeLicense(info *info) {
  324. fi, err := os.Stat(info.file)
  325. if os.IsNotExist(err) {
  326. fmt.Println("skipping (does not exist)", info.file)
  327. return
  328. }
  329. if err != nil {
  330. log.Fatalf("error stat'ing %s: %v\n", info.file, err)
  331. }
  332. content, err := ioutil.ReadFile(info.file)
  333. if err != nil {
  334. log.Fatalf("error reading %s: %v\n", info.file, err)
  335. }
  336. // Construct new file content.
  337. buf := new(bytes.Buffer)
  338. licenseT.Execute(buf, info)
  339. if m := licenseCommentRE.FindIndex(content); m != nil && m[0] == 0 {
  340. buf.Write(content[:m[0]])
  341. buf.Write(content[m[1]:])
  342. } else {
  343. buf.Write(content)
  344. }
  345. // Write it to the file.
  346. if bytes.Equal(content, buf.Bytes()) {
  347. fmt.Println("skipping (no changes)", info.file)
  348. return
  349. }
  350. fmt.Println("writing", info.ShortLicense(), info.file)
  351. if err := ioutil.WriteFile(info.file, buf.Bytes(), fi.Mode()); err != nil {
  352. log.Fatalf("error writing %s: %v", info.file, err)
  353. }
  354. }
  355. func doLines(cmd *exec.Cmd, f func(string)) error {
  356. stdout, err := cmd.StdoutPipe()
  357. if err != nil {
  358. return err
  359. }
  360. if err := cmd.Start(); err != nil {
  361. return err
  362. }
  363. s := bufio.NewScanner(stdout)
  364. for s.Scan() {
  365. f(s.Text())
  366. }
  367. if s.Err() != nil {
  368. return s.Err()
  369. }
  370. if err := cmd.Wait(); err != nil {
  371. return fmt.Errorf("%v (for %s)", err, strings.Join(cmd.Args, " "))
  372. }
  373. return nil
  374. }