forked from traefik/yaegi
/
extract.go
128 lines (108 loc) · 2.58 KB
/
extract.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/MustangYan/yaegi/extract"
)
func extractCmd(arg []string) error {
var licensePath string
var name string
var exclude string
var include string
var tag string
eflag := flag.NewFlagSet("run", flag.ContinueOnError)
eflag.StringVar(&licensePath, "license", "", "path to a LICENSE file")
eflag.StringVar(&name, "name", "", "the namespace for the extracted symbols")
eflag.StringVar(&exclude, "exclude", "", "comma separated list of regexp matching symbols to exclude")
eflag.StringVar(&include, "include", "", "comma separated list of regexp matching symbols to include")
eflag.StringVar(&tag, "tag", "", "comma separated list of build tags to be added to the created package")
eflag.Usage = func() {
fmt.Println("Usage: yaegi extract [options] packages...")
fmt.Println("Options:")
eflag.PrintDefaults()
}
if err := eflag.Parse(arg); err != nil {
return err
}
args := eflag.Args()
if len(args) == 0 {
return fmt.Errorf("missing package")
}
license, err := genLicense(licensePath)
if err != nil {
return err
}
wd, err := os.Getwd()
if err != nil {
return err
}
if name == "" {
name = filepath.Base(wd)
}
ext := extract.Extractor{
Dest: name,
License: license,
}
if tag != "" {
ext.Tag = strings.Split(tag, ",")
}
if exclude != "" {
ext.Exclude = strings.Split(exclude, ",")
}
if include != "" {
ext.Include = strings.Split(include, ",")
}
r := strings.NewReplacer("/", "-", ".", "_")
for _, pkgIdent := range args {
var buf bytes.Buffer
importPath, err := ext.Extract(pkgIdent, name, &buf)
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
oFile := r.Replace(importPath) + ".go"
f, err := os.Create(oFile)
if err != nil {
return err
}
if _, err := io.Copy(f, &buf); err != nil {
_ = f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
}
return nil
}
// genLicense generates the correct LICENSE header text from the provided
// path to a LICENSE file.
func genLicense(fname string) (string, error) {
if fname == "" {
return "", nil
}
f, err := os.Open(fname)
if err != nil {
return "", fmt.Errorf("could not open LICENSE file: %w", err)
}
defer func() { _ = f.Close() }()
license := new(strings.Builder)
sc := bufio.NewScanner(f)
for sc.Scan() {
txt := sc.Text()
if txt != "" {
txt = " " + txt
}
license.WriteString("//" + txt + "\n")
}
if sc.Err() != nil {
return "", fmt.Errorf("could not scan LICENSE file: %w", err)
}
return license.String(), nil
}