update-license.go 9.9 KB

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