update-license.go 8.7 KB

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