update-license.go 9.1 KB

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