update-license.go 10 KB

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