1
2
3
4
5 package codehost
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "internal/lazyregexp"
12 "io"
13 "io/fs"
14 "os"
15 "path/filepath"
16 "sort"
17 "strconv"
18 "strings"
19 "sync"
20 "sync/atomic"
21 "time"
22 "unicode"
23
24 "cmd/go/internal/base"
25 "cmd/go/internal/cfg"
26 "cmd/go/internal/lockedfile"
27 "cmd/go/internal/vcscmd"
28 "cmd/internal/par"
29
30 "golang.org/x/mod/semver"
31 )
32
33
34
35
36
37
38
39
40
41
42 type VCSError struct {
43 Err error
44 }
45
46 func (e *VCSError) Error() string { return e.Err.Error() }
47
48 func (e *VCSError) Unwrap() error { return e.Err }
49
50 func vcsErrorf(format string, a ...any) error {
51 return &VCSError{Err: fmt.Errorf(format, a...)}
52 }
53
54 type vcsCacheKey struct {
55 vcs string
56 remote string
57 local bool
58 }
59
60 func NewRepo(ctx context.Context, vcs, remote string, local bool) (Repo, error) {
61 return vcsRepoCache.Do(vcsCacheKey{vcs, remote, local}, func() (Repo, error) {
62 repo, err := newVCSRepo(ctx, vcs, remote, local)
63 if err != nil {
64 return nil, &VCSError{err}
65 }
66 return repo, nil
67 })
68 }
69
70 var vcsRepoCache par.ErrCache[vcsCacheKey, Repo]
71
72 type vcsRepo struct {
73 mu lockedfile.Mutex
74
75 remote string
76 cmd *vcsCmd
77 dir string
78 local bool
79
80 tagsOnce sync.Once
81 tags map[string]bool
82
83 branchesOnce sync.Once
84 branches map[string]bool
85
86 fetchOnce sync.Once
87 fetchErr error
88 fetched atomic.Bool
89
90 repoSumOnce sync.Once
91 repoSum string
92
93 statCache par.ErrCache[string, *RevInfo]
94 readFileCache par.ErrCache[[2]string, []byte]
95 }
96
97 func newVCSRepo(ctx context.Context, vcs, remote string, local bool) (Repo, error) {
98 if !local && (strings.HasPrefix(remote, "-") || strings.ContainsFunc(remote, unicode.IsControl)) {
99
100
101 return nil, fmt.Errorf("invalid vcs remote: %s %q", vcs, remote)
102 }
103 if vcs == "git" {
104 return newGitRepo(ctx, remote, local)
105 }
106 r := &vcsRepo{remote: remote, local: local}
107 cmd := vcsCmds[vcs]
108 if cmd == nil {
109 return nil, fmt.Errorf("unknown vcs: %s %s", vcs, remote)
110 }
111 r.cmd = cmd
112 if local {
113 info, err := os.Stat(remote)
114 if err != nil {
115 return nil, err
116 }
117 if !info.IsDir() {
118 return nil, fmt.Errorf("%s exists but is not a directory", remote)
119 }
120 r.dir = remote
121 r.mu.Path = r.dir + ".lock"
122 return r, nil
123 }
124 if !strings.Contains(remote, "://") {
125 return nil, fmt.Errorf("invalid vcs remote: %s %s", vcs, remote)
126 }
127 var err error
128 r.dir, r.mu.Path, err = WorkDir(ctx, vcsWorkDirType+vcs, r.remote)
129 if err != nil {
130 return nil, err
131 }
132
133 if cmd.init == nil {
134 return r, nil
135 }
136
137 unlock, err := r.mu.Lock()
138 if err != nil {
139 return nil, err
140 }
141 defer unlock()
142
143 if _, err := os.Stat(filepath.Join(r.dir, "."+vcs)); err != nil {
144 release, err := base.AcquireNet()
145 if err != nil {
146 return nil, err
147 }
148 init := cmd.init(r.remote)
149 _, err = run(ctx, r.dir, init)
150 if err == nil && cmd.postInit != nil {
151 err = cmd.postInit(ctx, r)
152 }
153 release()
154
155 if err != nil {
156 os.RemoveAll(r.dir)
157 return nil, err
158 }
159 }
160 return r, nil
161 }
162
163 const vcsWorkDirType = "vcs1."
164
165 type vcsCmd struct {
166 vcs string
167 init func(remote string) *vcscmd.Command
168 postInit func(context.Context, *vcsRepo) error
169 repoSum func(remote string) *vcscmd.Command
170 lookupRef func(remote, ref string) *vcscmd.Command
171 tags func(remote string) *vcscmd.Command
172 tagsNeedsFetch bool
173 tagRE *lazyregexp.Regexp
174 branches func(remote string) *vcscmd.Command
175 branchesNeedsFetch bool
176 branchRE *lazyregexp.Regexp
177 badLocalRevRE *lazyregexp.Regexp
178 statLocal func(rev, remote string) *vcscmd.Command
179 parseStat func(rev, out string) (*RevInfo, error)
180 fetch func() *vcscmd.Command
181 latest string
182 descendsFrom func(rev, tag string) *vcscmd.Command
183 recentTags func(rev string) *vcscmd.Command
184 readFile func(rev, file, remote string) *vcscmd.Command
185 readZip func(rev, subdir, dir, target string) *vcscmd.Command
186
187
188 doReadZip func(ctx context.Context, dst io.Writer, workDir, rev, subdir, remote string) error
189 }
190
191 var re = lazyregexp.New
192
193 var vcsCmds = map[string]*vcsCmd{
194 "hg": {
195 vcs: "hg",
196 repoSum: func(remote string) *vcscmd.Command {
197 return vcscmd.New("hg").Option("--config", hgRepoSumExt()).Add("goreposum").Operands(remote)
198 },
199 lookupRef: func(remote, ref string) *vcscmd.Command {
200 return vcscmd.New("hg").Option("--config", hgRepoSumExt()).Add("golookup").Operands(remote, ref)
201 },
202 init: func(remote string) *vcscmd.Command {
203 return vcscmd.New("hg", "init", ".")
204 },
205 postInit: hgAddRemote,
206 tags: func(remote string) *vcscmd.Command {
207 return vcscmd.New("hg", "tags", "-q")
208 },
209 tagsNeedsFetch: true,
210 tagRE: re(`(?m)^[^\n]+$`),
211 branches: func(remote string) *vcscmd.Command {
212 return vcscmd.New("hg", "branches", "-c", "-q")
213 },
214 branchesNeedsFetch: true,
215 branchRE: re(`(?m)^[^\n]+$`),
216 badLocalRevRE: re(`(?m)^(tip)$`),
217 statLocal: func(rev, remote string) *vcscmd.Command {
218 return hgLog(hgQuote(rev)).Add("-l1", "--template", "{node} {date|hgdate} {tags}")
219 },
220 parseStat: hgParseStat,
221 fetch: func() *vcscmd.Command {
222 return vcscmd.New("hg", "pull", "-f")
223 },
224 latest: "tip",
225 descendsFrom: func(rev, tag string) *vcscmd.Command {
226 return hgLog("ancestors(" + hgQuote(rev) + ") and " + hgQuote(tag))
227 },
228 recentTags: func(rev string) *vcscmd.Command {
229 return hgLog("ancestors("+hgQuote(rev)+") and tag()").Add("--template", "{tags}\n")
230 },
231 readFile: func(rev, file, remote string) *vcscmd.Command {
232 return vcscmd.New("hg", "cat").Option("--rev", rev).Operands(file)
233 },
234 readZip: func(rev, subdir, dir, target string) *vcscmd.Command {
235 c := vcscmd.New("hg", "archive", "-t", "zip", "--no-decode").Option("--rev", rev).Add("--prefix=prefix/")
236 if subdir != "" {
237 c.Option("--include", "path:"+subdir)
238 }
239 return c.Operands(target)
240 },
241 },
242
243 "svn": {
244 vcs: "svn",
245 init: nil,
246 tags: func(remote string) *vcscmd.Command {
247 return vcscmd.New("svn", "list").Operands(strings.TrimSuffix(remote, "/trunk") + "/tags")
248 },
249 tagRE: re(`(?m)^(.*?)/?$`),
250 statLocal: func(rev, remote string) *vcscmd.Command {
251 suffix := "@" + rev
252 if rev == "latest" {
253 suffix = "@"
254 }
255 return vcscmd.New("svn", "log", "-l1", "--xml").Operands(remote + suffix)
256 },
257 parseStat: svnParseStat,
258 latest: "latest",
259 readFile: func(rev, file, remote string) *vcscmd.Command {
260 return vcscmd.New("svn", "cat").Operands(remote + "/" + file + "@" + rev)
261 },
262 doReadZip: svnReadZip,
263 },
264
265 "fossil": {
266 vcs: "fossil",
267 init: func(remote string) *vcscmd.Command {
268 return vcscmd.New("fossil", "clone").Operands(remote, ".fossil")
269 },
270 fetch: func() *vcscmd.Command {
271 return vcscmd.New("fossil", "pull", "-R", ".fossil")
272 },
273 tags: func(remote string) *vcscmd.Command {
274 return vcscmd.New("fossil", "tag", "-R", ".fossil", "list")
275 },
276 tagRE: re(`XXXTODO`),
277 statLocal: func(rev, remote string) *vcscmd.Command {
278 return vcscmd.New("fossil", "info", "-R", ".fossil").Operands(rev)
279 },
280 parseStat: fossilParseStat,
281 latest: "trunk",
282 readFile: func(rev, file, remote string) *vcscmd.Command {
283 return vcscmd.New("fossil", "cat", "-R", ".fossil").Option("-r", rev).Operands(file)
284 },
285 readZip: func(rev, subdir, dir, target string) *vcscmd.Command {
286
287 c := vcscmd.New("fossil", "zip").Option("-R", filepath.Join(dir, ".fossil")).Add("--name", "prefix")
288 if subdir != "" && !strings.ContainsAny(subdir, "*?[],") {
289 c.Option("--include", subdir)
290 }
291 return c.Operands(rev, target)
292 },
293 },
294 }
295
296 func hgRepoSumExt() string {
297 return "extensions.goreposum=" + filepath.Join(cfg.GOROOT, "lib/hg/goreposum.py")
298 }
299
300 func hgLog(revset string) *vcscmd.Command {
301
302
303 return vcscmd.New("hg", "log").Option("--rev", " "+revset)
304 }
305
306 var hgRevsetEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`)
307
308
309 func hgQuote(rev string) string {
310 return `"` + hgRevsetEscaper.Replace(rev) + `"`
311 }
312
313 func (r *vcsRepo) loadTags(ctx context.Context) {
314 if r.cmd.tagsNeedsFetch {
315 r.fetchOnce.Do(func() { r.fetch(ctx) })
316 }
317
318 cmd := r.cmd.tags(r.remote)
319 out, err := run(ctx, r.dir, cmd)
320 if err != nil {
321 return
322 }
323
324
325 r.tags = make(map[string]bool)
326 for _, tag := range r.cmd.tagRE.FindAllString(string(out), -1) {
327 if r.cmd.badLocalRevRE != nil && r.cmd.badLocalRevRE.MatchString(tag) {
328 continue
329 }
330 r.tags[tag] = true
331 }
332 }
333
334 func (r *vcsRepo) loadBranches(ctx context.Context) {
335 if r.cmd.branches == nil {
336 return
337 }
338
339 if r.cmd.branchesNeedsFetch {
340 r.fetchOnce.Do(func() { r.fetch(ctx) })
341 }
342
343 cmd := r.cmd.branches(r.remote)
344 out, err := run(ctx, r.dir, cmd)
345 if err != nil {
346 return
347 }
348
349 r.branches = make(map[string]bool)
350 for _, branch := range r.cmd.branchRE.FindAllString(string(out), -1) {
351 if r.cmd.badLocalRevRE != nil && r.cmd.badLocalRevRE.MatchString(branch) {
352 continue
353 }
354 r.branches[branch] = true
355 }
356 }
357
358 func (r *vcsRepo) loadRepoSum(ctx context.Context) {
359 if r.cmd.repoSum == nil {
360 return
361 }
362 where := r.remote
363 if r.fetched.Load() {
364 where = "."
365 }
366 cmd := r.cmd.repoSum(where)
367 out, err := run(ctx, r.dir, cmd)
368 if err != nil {
369 return
370 }
371 r.repoSum = strings.TrimSpace(string(out))
372 }
373
374 func (r *vcsRepo) lookupRef(ctx context.Context, ref string) (string, error) {
375 if r.cmd.lookupRef == nil {
376 return "", fmt.Errorf("no lookupRef")
377 }
378 cmd := r.cmd.lookupRef(r.remote, ref)
379 out, err := run(ctx, r.dir, cmd)
380 if err != nil {
381 return "", err
382 }
383 return strings.TrimSpace(string(out)), nil
384 }
385
386
387 func (r *vcsRepo) repoSumOrigin(ctx context.Context) *Origin {
388 origin := &Origin{
389 VCS: r.cmd.vcs,
390 URL: r.remote,
391 RepoSum: r.repoSum,
392 }
393 r.repoSumOnce.Do(func() { r.loadRepoSum(ctx) })
394 origin.RepoSum = r.repoSum
395 return origin
396 }
397
398 func (r *vcsRepo) CheckReuse(ctx context.Context, old *Origin, subdir string) error {
399 if old == nil {
400 return fmt.Errorf("missing origin")
401 }
402 if old.VCS != r.cmd.vcs || old.URL != r.remote {
403 return fmt.Errorf("origin moved from %v %q to %v %q", old.VCS, old.URL, r.cmd.vcs, r.remote)
404 }
405 if old.Subdir != subdir {
406 return fmt.Errorf("origin moved from %v %q %q to %v %q %q", old.VCS, old.URL, old.Subdir, r.cmd.vcs, r.remote, subdir)
407 }
408
409 if old.Ref == "" && old.RepoSum == "" && old.Hash != "" {
410
411 hash, err := r.lookupRef(ctx, old.Hash)
412 if err == nil && hash == old.Hash {
413 return nil
414 }
415 if err != nil {
416 return fmt.Errorf("looking up hash: %v", err)
417 }
418 return fmt.Errorf("hash changed")
419 }
420
421 if old.Ref != "" && old.RepoSum == "" {
422 hash, err := r.lookupRef(ctx, old.Ref)
423 if err == nil && hash != "" && hash == old.Hash {
424 return nil
425 }
426 }
427
428 r.repoSumOnce.Do(func() { r.loadRepoSum(ctx) })
429 if r.repoSum != "" {
430 if old.RepoSum == "" {
431 return fmt.Errorf("non-specific origin")
432 }
433 if old.RepoSum != r.repoSum {
434 return fmt.Errorf("repo changed")
435 }
436 return nil
437 }
438 return fmt.Errorf("vcs %s: CheckReuse: %w", r.cmd.vcs, errors.ErrUnsupported)
439 }
440
441 func (r *vcsRepo) Tags(ctx context.Context, prefix string) (*Tags, error) {
442 unlock, err := r.mu.Lock()
443 if err != nil {
444 return nil, err
445 }
446 defer unlock()
447
448 r.tagsOnce.Do(func() { r.loadTags(ctx) })
449 tags := &Tags{
450 Origin: r.repoSumOrigin(ctx),
451 List: []Tag{},
452 }
453 for tag := range r.tags {
454 if strings.HasPrefix(tag, prefix) {
455 tags.List = append(tags.List, Tag{tag, ""})
456 }
457 }
458 sort.Slice(tags.List, func(i, j int) bool {
459 return tags.List[i].Name < tags.List[j].Name
460 })
461 return tags, nil
462 }
463
464 func (r *vcsRepo) Stat(ctx context.Context, rev string) (*RevInfo, error) {
465 return r.statCache.Do(rev, func() (*RevInfo, error) {
466 unlock, err := r.mu.Lock()
467 if err != nil {
468 return nil, err
469 }
470 defer unlock()
471
472 if rev == "latest" {
473 rev = r.cmd.latest
474 }
475 r.branchesOnce.Do(func() { r.loadBranches(ctx) })
476 if r.local {
477
478
479 return r.statLocal(ctx, rev)
480 }
481 revOK := (r.cmd.badLocalRevRE == nil || !r.cmd.badLocalRevRE.MatchString(rev)) && !r.branches[rev]
482 if revOK {
483 if info, err := r.statLocal(ctx, rev); err == nil {
484 return info, nil
485 }
486 }
487
488 r.fetchOnce.Do(func() { r.fetch(ctx) })
489 if r.fetchErr != nil {
490 return nil, r.fetchErr
491 }
492 info, err := r.statLocal(ctx, rev)
493 if err != nil {
494 return info, err
495 }
496 if !revOK {
497 info.Version = info.Name
498 }
499 return info, nil
500 })
501 }
502
503 func (r *vcsRepo) fetch(ctx context.Context) {
504 if r.cmd.fetch != nil {
505 release, err := base.AcquireNet()
506 if err != nil {
507 r.fetchErr = err
508 return
509 }
510 cmd := r.cmd.fetch()
511 _, r.fetchErr = run(ctx, r.dir, cmd)
512 release()
513 r.fetched.Store(true)
514 }
515 }
516
517 func (r *vcsRepo) statLocal(ctx context.Context, rev string) (*RevInfo, error) {
518 cmd := r.cmd.statLocal(rev, r.remote)
519 out, err := run(ctx, r.dir, cmd)
520 if err != nil {
521 info := &RevInfo{Origin: r.repoSumOrigin(ctx)}
522 return info, &UnknownRevisionError{Rev: rev}
523 }
524 info, err := r.cmd.parseStat(rev, string(out))
525 if err != nil {
526 return nil, err
527 }
528 if info.Origin == nil {
529 info.Origin = new(Origin)
530 }
531 info.Origin.VCS = r.cmd.vcs
532 info.Origin.URL = r.remote
533 info.Origin.Ref = rev
534 if strings.HasPrefix(info.Name, rev) && len(rev) >= 12 {
535 info.Origin.Ref = ""
536 }
537 return info, nil
538 }
539
540 func (r *vcsRepo) Latest(ctx context.Context) (*RevInfo, error) {
541 return r.Stat(ctx, "latest")
542 }
543
544 func (r *vcsRepo) ReadFile(ctx context.Context, rev, file string, maxSize int64) ([]byte, error) {
545 return r.readFileCache.Do([2]string{rev, file}, func() ([]byte, error) {
546 if rev == "latest" {
547 rev = r.cmd.latest
548 }
549 info, err := r.Stat(ctx, rev)
550 if err != nil {
551 return nil, err
552 }
553 if r.cmd.vcs == "hg" {
554 rev = info.Name
555 }
556
557
558 unlock, err := r.mu.Lock()
559 if err != nil {
560 return nil, err
561 }
562 defer unlock()
563
564 cmd := r.cmd.readFile(rev, file, r.remote)
565 out, err := run(ctx, r.dir, cmd)
566 if err != nil {
567 return nil, fs.ErrNotExist
568 }
569 return out, nil
570 })
571 }
572
573 func (r *vcsRepo) RecentTag(ctx context.Context, rev, prefix string, allowed func(string) bool) (tag string, err error) {
574
575
576 unlock, err := r.mu.Lock()
577 if err != nil {
578 return "", err
579 }
580
581 if r.cmd.recentTags == nil {
582 unlock()
583 return "", vcsErrorf("vcs %s: RecentTag: %w", r.cmd.vcs, errors.ErrUnsupported)
584 }
585 cmd := r.cmd.recentTags(rev)
586 out, err := run(ctx, r.dir, cmd)
587 unlock()
588 if err != nil {
589 return "", err
590 }
591
592 highest := ""
593 for _, tag := range strings.Fields(string(out)) {
594 if !strings.HasPrefix(tag, prefix) || !allowed(tag) {
595 continue
596 }
597 semtag := tag[len(prefix):]
598 if semver.Compare(semtag, highest) > 0 {
599 highest = semtag
600 }
601 }
602 if highest != "" {
603 return prefix + highest, nil
604 }
605 return "", nil
606 }
607
608 func (r *vcsRepo) DescendsFrom(ctx context.Context, rev, tag string) (bool, error) {
609 unlock, err := r.mu.Lock()
610 if err != nil {
611 return false, err
612 }
613 defer unlock()
614
615 if r.cmd.descendsFrom == nil {
616 return false, vcsErrorf("vcs %s: DescendsFrom: %w", r.cmd.vcs, errors.ErrUnsupported)
617 }
618
619 cmd := r.cmd.descendsFrom(rev, tag)
620 out, err := run(ctx, r.dir, cmd)
621 if err != nil {
622 return false, err
623 }
624 return strings.TrimSpace(string(out)) != "", nil
625 }
626
627 func (r *vcsRepo) ReadZip(ctx context.Context, rev, subdir string, maxSize int64) (zip io.ReadCloser, err error) {
628 if r.cmd.readZip == nil && r.cmd.doReadZip == nil {
629 return nil, vcsErrorf("vcs %s: ReadZip: %w", r.cmd.vcs, errors.ErrUnsupported)
630 }
631
632 if rev == "latest" {
633 rev = r.cmd.latest
634 }
635 info, err := r.Stat(ctx, rev)
636 if err != nil {
637 return nil, err
638 }
639 if r.cmd.vcs == "hg" {
640 rev = info.Name
641 }
642
643 unlock, err := r.mu.Lock()
644 if err != nil {
645 return nil, err
646 }
647 defer unlock()
648
649 f, err := os.CreateTemp("", "go-readzip-*.zip")
650 if err != nil {
651 return nil, err
652 }
653 if r.cmd.doReadZip != nil {
654 lw := &limitedWriter{
655 W: f,
656 N: maxSize,
657 ErrLimitReached: errors.New("ReadZip: encoded file exceeds allowed size"),
658 }
659 err = r.cmd.doReadZip(ctx, lw, r.dir, rev, subdir, r.remote)
660 if err == nil {
661 _, err = f.Seek(0, io.SeekStart)
662 }
663 } else if r.cmd.vcs == "fossil" {
664
665
666
667
668 cmd := r.cmd.readZip(rev, subdir, r.dir, filepath.Base(f.Name()))
669 _, err = run(ctx, filepath.Dir(f.Name()), cmd)
670 } else {
671 cmd := r.cmd.readZip(rev, subdir, r.dir, f.Name())
672 _, err = run(ctx, r.dir, cmd)
673 }
674 if err != nil {
675 f.Close()
676 os.Remove(f.Name())
677 return nil, err
678 }
679 return &deleteCloser{f}, nil
680 }
681
682
683 type deleteCloser struct {
684 *os.File
685 }
686
687 func (d *deleteCloser) Close() error {
688 defer os.Remove(d.File.Name())
689 return d.File.Close()
690 }
691
692 func hgAddRemote(ctx context.Context, r *vcsRepo) error {
693
694 return os.WriteFile(filepath.Join(r.dir, ".hg/hgrc"), []byte(fmt.Sprintf("[paths]\ndefault = %s\n", r.remote)), 0666)
695 }
696
697 func hgParseStat(rev, out string) (*RevInfo, error) {
698 f := strings.Fields(out)
699 if len(f) < 3 {
700 return nil, vcsErrorf("unexpected response from hg log: %q", out)
701 }
702 hash := f[0]
703 version := rev
704 if strings.HasPrefix(hash, version) {
705 version = hash
706 }
707 t, err := strconv.ParseInt(f[1], 10, 64)
708 if err != nil {
709 return nil, vcsErrorf("invalid time from hg log: %q", out)
710 }
711
712 var tags []string
713 for _, tag := range f[3:] {
714 if tag != "tip" {
715 tags = append(tags, tag)
716 }
717 }
718 sort.Strings(tags)
719
720 info := &RevInfo{
721 Origin: &Origin{Hash: hash},
722 Name: hash,
723 Short: ShortenSHA1(hash),
724 Time: time.Unix(t, 0).UTC(),
725 Version: version,
726 Tags: tags,
727 }
728 return info, nil
729 }
730
731 func fossilParseStat(rev, out string) (*RevInfo, error) {
732 for line := range strings.SplitSeq(out, "\n") {
733 if strings.HasPrefix(line, "uuid:") || strings.HasPrefix(line, "hash:") {
734 f := strings.Fields(line)
735 if len(f) != 5 || len(f[1]) != 40 || f[4] != "UTC" {
736 return nil, vcsErrorf("unexpected response from fossil info: %q", line)
737 }
738 t, err := time.Parse(time.DateTime, f[2]+" "+f[3])
739 if err != nil {
740 return nil, vcsErrorf("unexpected response from fossil info: %q", line)
741 }
742 hash := f[1]
743 version := rev
744 if strings.HasPrefix(hash, version) {
745 version = hash
746 }
747 info := &RevInfo{
748 Origin: &Origin{Hash: hash},
749 Name: hash,
750 Short: ShortenSHA1(hash),
751 Time: t,
752 Version: version,
753 }
754 return info, nil
755 }
756 }
757 return nil, vcsErrorf("unexpected response from fossil info: %q", out)
758 }
759
760 type limitedWriter struct {
761 W io.Writer
762 N int64
763 ErrLimitReached error
764 }
765
766 func (l *limitedWriter) Write(p []byte) (n int, err error) {
767 if l.N > 0 {
768 max := len(p)
769 if l.N < int64(max) {
770 max = int(l.N)
771 }
772 n, err = l.W.Write(p[:max])
773 l.N -= int64(n)
774 if err != nil || n >= len(p) {
775 return n, err
776 }
777 }
778
779 return n, l.ErrLimitReached
780 }
781
View as plain text