| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package ripper |
| 16 |
|
| 17 |
import ( |
| 18 |
"bufio" |
| 19 |
"bytes" |
| 20 |
"os" |
| 21 |
"regexp" |
| 22 |
) |
| 23 |
|
| 24 |
type diction struct { |
| 25 |
skip *regexp.Regexp |
| 26 |
end *regexp.Regexp |
| 27 |
begin *regexp.Regexp |
| 28 |
} |
| 29 |
|
| 30 |
func readFile(absPath string, dctn *diction) (content string, err error) { |
| 31 |
var f *os.File |
| 32 |
f, err = os.Open(absPath) |
| 33 |
if err != nil || f == nil { |
| 34 |
return |
| 35 |
} |
| 36 |
|
| 37 |
defer f.Close() |
| 38 |
scanner := bufio.NewScanner(f) |
| 39 |
|
| 40 |
results := [][]byte{} |
| 41 |
|
| 42 |
canSkip := dctn.skip != nil |
| 43 |
canEnd := dctn.end != nil |
| 44 |
canBegin := dctn.begin != nil |
| 45 |
|
| 46 |
if canBegin { |
| 47 |
for scanner.Scan() { |
| 48 |
lineBytes := scanner.Bytes() |
| 49 |
if dctn.begin.Match(lineBytes) { |
| 50 |
results = append(results, lineBytes) |
| 51 |
break |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
for scanner.Scan() { |
| 57 |
lineBytes := scanner.Bytes() |
| 58 |
if canEnd && dctn.end.Match(lineBytes) { |
| 59 |
break |
| 60 |
} |
| 61 |
if canSkip && dctn.skip.Match(lineBytes) { |
| 62 |
continue |
| 63 |
} |
| 64 |
|
| 65 |
results = append(results, lineBytes) |
| 66 |
} |
| 67 |
|
| 68 |
joined := bytes.Join(results, []byte{'\n'}) |
| 69 |
content = string(joined) |
| 70 |
return |
| 71 |
} |
| 72 |
|
| 73 |
func ApacheTopLicenseRip(absPath string) (content string, err error) { |
| 74 |
var begin, end *regexp.Regexp |
| 75 |
|
| 76 |
begin, err = regexp.Compile("^//\\s*Copyright") |
| 77 |
if err != nil { |
| 78 |
return |
| 79 |
} |
| 80 |
|
| 81 |
end, err = regexp.Compile("^package") |
| 82 |
if err != nil { |
| 83 |
return |
| 84 |
} |
| 85 |
|
| 86 |
dctn := diction{ |
| 87 |
skip: nil, |
| 88 |
end: end, |
| 89 |
begin: begin, |
| 90 |
} |
| 91 |
|
| 92 |
return readFile(absPath, &dctn) |
| 93 |
} |