update-license.go 9.1 KB

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