-
Notifications
You must be signed in to change notification settings - Fork 55
/
env.go
1539 lines (1389 loc) · 43.7 KB
/
env.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package hermit
import (
"bytes"
"crypto/sha256"
"embed"
"encoding/hex"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"syscall"
"time"
"github.com/alecthomas/hcl"
"github.com/kballard/go-shellquote"
"github.com/cashapp/hermit/cache"
"github.com/cashapp/hermit/envars"
"github.com/cashapp/hermit/errors"
"github.com/cashapp/hermit/internal/system"
"github.com/cashapp/hermit/manifest"
"github.com/cashapp/hermit/platform"
"github.com/cashapp/hermit/shell"
"github.com/cashapp/hermit/sources"
"github.com/cashapp/hermit/state"
"github.com/cashapp/hermit/ui"
"github.com/cashapp/hermit/util"
)
// Reset environment variables.
var (
//go:embed files/script.sha256
sha256Db string
// ScriptSHAs contains the default known valid SHA256 sums for bin/activate-hermit and bin/hermit.
ScriptSHAs = tidySha256Db(sha256Db)
//go:embed files
files embed.FS
// InstallerTemplateSource is a string containing the installer template
//go:embed "files/install.sh.tmpl"
InstallerTemplateSource string
// UserStateDir should be passed to Open()/Init() in most cases.
UserStateDir = func() string {
// Check if state dir is explicitly set
explicit := os.Getenv("HERMIT_STATE_DIR")
if explicit != "" {
return explicit
}
cache, err := system.UserCacheDir()
if err != nil {
panic(fmt.Sprintf("could not find user cache dir: %s", err))
}
return filepath.Join(cache, "hermit")
}()
)
// Files to copy into the env.
var envBinFiles = map[string]os.FileMode{
"README.hermit.md": 0600,
"activate-hermit": 0700,
"activate-hermit.fish": 0700,
"hermit": 0700,
}
//go:generate stringer -linecomment -type CleanMask
// CleanMask is a bitmask specifying which parts of a hermit system to clean.
type CleanMask int
// Bitmask for what to clean.
const (
CleanBin CleanMask = 1 << iota // bin
CleanPackages // packages
CleanCache // cache
CleanAll CleanMask = ^0 // all
CleanTransient = CleanAll &^ CleanBin // transient
)
// Config for a Hermit environment.
type Config struct {
Envars envars.Envars `hcl:"env,optional" help:"Extra environment variables."`
Sources []string `hcl:"sources,optional" help:"Package manifest sources."`
ManageGit bool `hcl:"manage-git,optional" default:"true" help:"Whether Hermit should automatically 'git add' new packages."`
InheritParent bool `hcl:"inherit-parent,optional" default:"false" help:"Whether this environment inherits a potential parent environment from one of the parent directories"`
AddIJPlugin bool `hcl:"idea,optional" default:"false" help:"Whether Hermit should automatically add the IntelliJ IDEA plugin."`
GitHubTokenAuth GitHubTokenAuthConfig `hcl:"github-token-auth,block" help:"When to use GitHub token authentication."`
}
// GitHubTokenAuthConfig configures under what conditions
// GitHub token authentication should be used.
type GitHubTokenAuthConfig struct {
Match []string `hcl:"match,optional" help:"One or more glob patterns. If any of these match the 'owner/repo' pair of a GitHub repository, the GitHub token from the current environment will be used to fetch their artifacts."`
}
// Env is a Hermit environment.
type Env struct {
envDir string
useGit bool
state *state.State
binDir string // Path to bin directory for the environment.
ephemeralEnvars envars.Ops
config *Config
configFile string
httpClient *http.Client
scriptSums []string
// Lazily initialized fields
lazyResolver *manifest.Resolver
lazySources *sources.Sources
packageSource cache.PackageSourceSelector
}
//go:embed files/externalDependencies.xml
var extDepData []byte
// Init a new Env.
func Init(l *ui.UI, env string, distURL string, stateDir string, config Config, installScriptSHA string) error {
env = util.RealPath(env)
l.Infof("Creating new Hermit environment in %s", env)
vars := map[string]string{
"HERMIT_DEFAULT_DIST_URL": distURL,
"HERMIT_INSTALL_SCRIPT_SHA256": installScriptSHA,
}
bin := filepath.Join(env, "bin")
if err := os.Mkdir(bin, os.ModePerm); err != nil && !os.IsExist(err) { //nolint:gosec
return errors.WithStack(err)
}
if err := os.MkdirAll(stateDir, os.ModePerm); err != nil && !os.IsExist(err) { //nolint:gosec
return errors.WithStack(err)
}
sourcesDir := filepath.Join(stateDir, "sources")
if err := os.MkdirAll(sourcesDir, os.ModePerm); err != nil && !os.IsExist(err) { //nolint:gosec
return errors.WithStack(err)
}
useGit := config.ManageGit && isEnvAGitRepo(env)
b := l.Task(filepath.Base(env))
for file, perm := range envBinFiles {
l.Infof(" -> %s", filepath.Join(env, "bin", file))
if err := writeFileToEnvBin(b, useGit, file, env, vars, perm); err != nil {
return err
}
}
if config.AddIJPlugin {
ideaPath := filepath.Join(env, ".idea")
extDepPath := filepath.Join(ideaPath, "externalDependencies.xml")
if _, err := os.Stat(extDepPath); errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(ideaPath, os.ModePerm); err != nil && !os.IsExist(err) { //nolint:gosec
return errors.WithStack(err)
}
err = os.WriteFile(extDepPath, extDepData, 0600)
if err != nil {
return errors.WithStack(err)
}
if useGit {
if err = util.RunInDir(b, env, "git", "add", "-f", extDepPath); err != nil {
return errors.WithStack(err)
}
}
} else {
l.Infof("IntelliJ IDEA configuration already exists; skipping adding configuration.")
}
}
// Create a configuration file.
configPath := filepath.Join(bin, "hermit.hcl")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
l.Infof(" -> %s", configPath)
data, err := hcl.Marshal(&config)
if err != nil {
return errors.WithStack(err)
}
err = os.WriteFile(configPath, data, 0600)
if err != nil {
return errors.WithStack(err)
}
if useGit {
if err = util.RunInDir(b, env, "git", "add", "-f", filepath.Join(bin, "hermit.hcl")); err != nil {
return errors.WithStack(err)
}
}
}
l.Infof(`
Hermit environment initialised in %s
To activate the environment run:
. %s/bin/activate-hermit
Then run the following to list available commands:
hermit --help
To deactivate the environment run:
deactivate-hermit
For more information please refer to https://github.com/cashapp/hermit
`, env, env)
return nil
}
// EnvDirFromProxyLink finds a Hermit environment given a proxy symlink.
func EnvDirFromProxyLink(executable string) (string, error) {
links, err := util.ResolveSymlinks(executable)
if err != nil {
return "", errors.WithStack(err)
}
last, err := filepath.EvalSymlinks(links[len(links)-1])
if err != nil {
return "", errors.WithStack(err)
}
if filepath.Base(last) != "hermit" {
return "", errors.Errorf("binary is not a Hermit symlink: %s", links[0])
}
last = filepath.Dir(last)
if filepath.Base(last) != "bin" {
return "", errors.Errorf("Hermit not in a bin directory: %s", links[0])
}
last = filepath.Dir(last)
return last, nil
}
// FindEnvDir finds the highest priority active Hermit environment
func FindEnvDir(binary string) (envDir string, err error) {
// Prefer an adjacent environment
envDir, err = EnvDirFromProxyLink(binary)
if err == nil {
return
}
// Fallback to the environment from the environment variable
envDir = os.Getenv("HERMIT_ENV")
if envDir != "" {
return envDir, nil
}
// Pass up the error from EnvDirFromProxyLink
return
}
func getSources(l *ui.UI, envDir string, config *Config, state *state.State, defaultSources []string) (*sources.Sources, error) {
configuredSources := config.Sources
if config.Sources == nil {
configuredSources = defaultSources
}
ss, err := sources.ForURIs(l, state.SourcesDir(), envDir, configuredSources)
if err != nil {
return nil, errors.WithStack(err)
}
// Always include the builtin sources required by Hermit.
ss.Prepend(state.Config().Builtin)
return ss, nil
}
func readConfig(configFile string) (*Config, error) {
config := &Config{Envars: map[string]string{}, ManageGit: true}
source, err := os.ReadFile(configFile)
if !os.IsNotExist(err) {
if err != nil {
return nil, errors.Wrap(err, "couldn't load environment config")
}
err = hcl.Unmarshal(source, config)
if err != nil {
return nil, errors.Wrap(err, configFile)
}
}
return config, nil
}
// EnvInfo holds information about the current Hermit environment.
type EnvInfo struct {
// Root is the root environment directory.
// This contains the bin/hermit.hcl.
Root string
// BinDir is the path to the binary directory of the environment.
BinDir string
// ConfigFile is the path to the environment's configuration file.
ConfigFile string
// Config is the parsed representation of ConfigFile.
Config *Config
}
// LoadEnvInfo loads information about the environment rooted at the given
// directory.
func LoadEnvInfo(envDir string) (*EnvInfo, error) {
envDir = util.RealPath(envDir)
binDir := filepath.Join(envDir, "bin")
configFile := filepath.Join(binDir, "hermit.hcl")
config, err := readConfig(configFile)
if err != nil {
return nil, errors.Wrap(err, configFile)
}
return &EnvInfo{
Root: envDir,
BinDir: binDir,
ConfigFile: configFile,
Config: config,
}, nil
}
// OpenEnv opens a Hermit environment.
//
// The environment may not exist, in which case this will succeed but subsequent operations will fail.
//
// "scriptSums" contains all known SHA256 checksums for "bin/hermit" and "bin/activate-hermit" scripts.
func OpenEnv(
info *EnvInfo,
state *state.State,
packageSource cache.PackageSourceSelector,
ephemeral envars.Envars,
httpClient *http.Client,
scriptSums []string,
) (*Env, error) {
useGit := info.Config.ManageGit && isEnvAGitRepo(info.Root)
if len(scriptSums) == 0 {
scriptSums = ScriptSHAs
}
return &Env{
packageSource: packageSource,
config: info.Config,
envDir: info.Root,
useGit: useGit,
state: state,
binDir: info.BinDir,
configFile: info.ConfigFile,
ephemeralEnvars: envars.Infer(ephemeral.System()),
httpClient: httpClient,
scriptSums: scriptSums,
}, nil
}
// Root directory of the environment.
func (e *Env) Root() string {
return e.envDir
}
// Verify contains valid Hermit scripts.
func (e *Env) Verify() error {
next:
for _, file := range []string{"activate-hermit", "activate-hermit.fish", "hermit"} {
path := filepath.Join(e.binDir, file)
hasher := sha256.New()
r, err := os.Open(path)
if os.IsNotExist(err) {
if file == "activate-hermit.fish" {
// Fish support was added later. Older hermit envs won't have it.
continue next
}
return errors.Wrapf(err, "%s is missing, not a Hermit environment?", path)
} else if err != nil {
return errors.WithStack(err)
}
_, err = io.Copy(hasher, r)
_ = r.Close()
if err != nil {
return errors.WithStack(err)
}
hash := hex.EncodeToString(hasher.Sum(nil))
for _, candidate := range e.scriptSums {
if hash == candidate {
continue next
}
}
return errors.Errorf("%s has an unknown SHA256 signature (%s); verify that you trust this environment and run 'hermit init %s'", path, hash, e.envDir)
}
return nil
}
// Trigger an event for all installed packages.
func (e *Env) Trigger(l *ui.UI, event manifest.Event) (messages []string, err error) {
pkgs, err := e.ListInstalled(l)
if err != nil {
return nil, err
}
for _, pkg := range pkgs {
pkgMessages, err := e.TriggerForPackage(l, event, pkg)
if err != nil {
return nil, err
}
messages = append(messages, pkgMessages...)
}
return messages, nil
}
// TriggerForPackage triggers an event for a single package.
func (e *Env) TriggerForPackage(l *ui.UI, event manifest.Event, pkg *manifest.Package) (messages []string, err error) {
messages, err = pkg.Trigger(l, event)
if err != nil {
return nil, errors.Wrapf(err, "%s: on %s", pkg, event)
}
return messages, nil
}
// ValidateManifests from all sources.
func (e *Env) ValidateManifests(l *ui.UI) (manifest.ManifestErrors, error) {
resolver, err := e.resolver(l)
if err != nil {
return nil, errors.WithStack(err)
}
if err := resolver.LoadAll(); err != nil {
return nil, errors.WithStack(err)
}
return resolver.Errors(), nil
}
// LinkedBinaries lists just the binaries installed in the environment.
func (e *Env) LinkedBinaries(pkg *manifest.Package) (binaries []string, err error) {
files, err := os.ReadDir(e.binDir)
if err != nil {
return nil, errors.WithStack(err)
}
for _, file := range files {
bin := filepath.Join(e.binDir, file.Name())
link, err := os.Readlink(bin)
if err != nil || !strings.HasSuffix(link, ".pkg") {
continue
}
ref := e.referenceFromBinLink(link)
if ref.String() == pkg.String() {
binaries = append(binaries, bin)
}
}
return
}
// Uninstall uninstalls a single package.
func (e *Env) Uninstall(l *ui.UI, pkg *manifest.Package) (*shell.Changes, error) {
return e.uninstall(l.Task(pkg.Reference.String()), pkg)
}
func (e *Env) uninstall(l *ui.Task, pkg *manifest.Package) (*shell.Changes, error) {
log := l.SubTask("uninstall")
log.Infof("Uninstalling %s", pkg)
// Is it installed?
link := e.pkgLink(pkg)
if _, err := os.Stat(link); os.IsNotExist(err) {
return nil, errors.Errorf("package %s is not installed", pkg)
}
ops := e.envarsForPackages(pkg)
// Remove symlinks in the bin dir.
err := e.unlinkPackage(l, pkg)
if err != nil {
return nil, errors.WithStack(err)
}
changes := shell.NewChanges(envars.Parse(os.Environ()))
changes.Remove = ops
return changes, nil
}
func (e *Env) unlinkPackage(l *ui.Task, pkg *manifest.Package) error {
link := e.pkgLink(pkg)
binaries, err := e.LinkedBinaries(pkg)
if err != nil {
return errors.WithStack(err)
}
task := l.SubProgress("unlink", 1+len(binaries))
defer task.Done()
task.Debugf("Uninstalling %s", pkg)
err = e.unlink(task, link)
if err != nil && !os.IsNotExist(err) {
return errors.WithStack(err)
}
task.Add(1)
for _, link := range binaries {
err := e.unlink(task, link)
task.Add(1)
if err != nil && !os.IsNotExist(err) {
return errors.WithStack(err)
}
}
return nil
}
func (e *Env) unlink(l *ui.Task, path string) error {
if e.useGit {
err := util.RunInDir(l, e.envDir, "git", "rm", "-f", path)
if err != nil {
l.Errorf("non-fatal: %s", err)
}
}
l.Tracef("rm %s", path)
return os.Remove(path)
}
// Test the sanity of a package using the configured test shell fragment.
func (e *Env) Test(l *ui.UI, pkg *manifest.Package) error {
task := l.Task(pkg.Reference.String())
if pkg.Test == "" {
return nil
}
args, err := shellquote.Split(pkg.Test)
if err != nil {
return errors.Wrapf(err, "%s: invalid test shell fragment %q", pkg.String(), pkg.Test)
}
if err = e.state.CacheAndUnpack(task, pkg); err != nil {
return errors.WithStack(err)
}
bins, err := pkg.ResolveBinaries()
if err != nil {
return errors.WithStack(err)
}
found := false
for _, bin := range bins {
if filepath.Base(bin) == args[0] {
args[0] = bin
found = true
break
}
}
if !found {
return errors.Errorf("couldn't find test executable %q in package %s", args[0], pkg)
}
cmd, out := util.Command(task, args...)
deps, err := e.ensureRuntimeDepsPresent(l, pkg)
if err != nil {
return errors.WithStack(err)
}
cmd.Env = e.envarsFromOps(true, e.allEnvarOpsForPackages(deps, pkg))
err = cmd.Run()
if err != nil {
return errors.Wrap(err, out.String())
}
return nil
}
// Unpack but do not install package.
func (e *Env) Unpack(l *ui.Task, p *manifest.Package) error {
task := l.SubTask(p.Reference.String())
return e.state.CacheAndUnpack(task, p)
}
// Install package. If a package with same name exists, uninstall it first.
func (e *Env) Install(l *ui.UI, pkg *manifest.Package) (*shell.Changes, error) {
task := l.Task(pkg.Reference.String())
installed, err := e.ListInstalled(l)
if err != nil {
return nil, errors.WithStack(err)
}
if err := pkg.EnsureSupported(); err != nil {
return nil, errors.Wrapf(err, "install failed")
}
allChanges := shell.NewChanges(envars.Parse(os.Environ()))
didUninstall := false
for _, ipkg := range installed {
if ipkg.Reference.Name == pkg.Reference.Name {
changes, err := e.uninstall(task, ipkg)
if err != nil {
return nil, errors.WithStack(err)
}
allChanges = allChanges.Merge(changes)
didUninstall = true
}
}
if !didUninstall && len(pkg.UnsupportedPlatforms) > 0 {
resp, err := l.Confirmation("%s is not supported on these Hermit platforms: %s, are you sure you want to install it? [y/N]", pkg.Reference, pkg.UnsupportedPlatforms)
if err != nil {
return nil, errors.WithStack(err)
}
if !resp {
return allChanges, nil
}
}
changes, err := e.install(l, pkg)
if err != nil {
return nil, errors.WithStack(err)
}
return allChanges.Merge(changes), nil
}
// resolveRuntimeDependencies checks all runtime dependencies for a package are available.
//
// Aggregate and collect the package names and binaries of all runtime dependencies to avoid collisions.
func (e *Env) resolveRuntimeDependencies(l *ui.UI, p *manifest.Package, aggregate map[string]*manifest.Package, bins map[string]*manifest.Package) error {
var depPkgs []*manifest.Package
// Explicitly specified runtime-dependencies in the package.
for _, ref := range p.RuntimeDeps {
previous := aggregate[ref.Name]
if previous != nil && previous.Reference.Compare(ref) != 0 {
return errors.Errorf("two conflicting runtime-dependencies: %s vs %s", ref, previous.Reference)
}
depPkg, err := e.Resolve(l, manifest.ExactSelector(ref), true)
if err != nil {
return errors.WithStack(err)
}
depPkgs = append(depPkgs, depPkg)
}
for _, depPkg := range depPkgs {
for _, bin := range depPkg.Binaries {
base := filepath.Base(bin)
if previous, ok := bins[base]; ok && !previous.Reference.Match(depPkg.Reference) {
return errors.Errorf("conflicting binary %q in multiple runtime dependencies: %s and %s", bin, previous.Reference, depPkg.Reference)
}
bins[base] = depPkg
}
aggregate[depPkg.Reference.Name] = depPkg
if err := e.resolveRuntimeDependencies(l, depPkg, aggregate, bins); err != nil {
return err
}
}
return nil
}
func (e *Env) ensureRuntimeDepsPresent(l *ui.UI, p *manifest.Package) ([]*manifest.Package, error) {
deps := map[string]*manifest.Package{}
err := e.resolveRuntimeDependencies(l, p, deps, map[string]*manifest.Package{})
if err != nil {
return nil, errors.WithStack(err)
}
result := make([]*manifest.Package, 0, len(deps))
for _, pkg := range deps {
if err := e.state.CacheAndUnpack(l.Task(p.Reference.String()), pkg); err != nil {
return nil, errors.WithStack(err)
}
result = append(result, pkg)
}
return result, nil
}
// Update timestamps for runtime dependencies.
func (e *Env) writePackageState(pkgs ...*manifest.Package) error {
for _, pkg := range pkgs {
if err := e.state.WritePackageState(pkg); err != nil {
return errors.WithStack(err)
}
}
return nil
}
// install a package
func (e *Env) install(l *ui.UI, p *manifest.Package) (*shell.Changes, error) {
task := l.Task(p.Reference.String())
pkgs, err := e.ensureRuntimeDepsPresent(l, p)
if err != nil {
return nil, errors.WithStack(err)
}
p.UpdatedAt = time.Now()
log := task.SubTask("install")
log.Infof("Installing %s", p)
log.Debugf("From %s", p.Source)
log.Debugf("To %s", p.Dest)
err = e.state.CacheAndUnpack(task, p)
if err != nil {
return nil, errors.WithStack(err)
}
if _, err := os.Stat(e.pkgLink(p)); os.IsNotExist(err) {
if err = e.linkPackage(task, p); err != nil {
return nil, errors.WithStack(err)
}
pkgs = append(pkgs, p)
}
ops := e.envarsForPackages(p)
changes := shell.NewChanges(envars.Parse(os.Environ()))
changes.Add = ops
return changes, errors.WithStack(e.writePackageState(pkgs...))
}
// Upgrade package.
//
// If an upgrade does not occur, returns all nils.
func (e *Env) Upgrade(l *ui.UI, pkg *manifest.Package) (*shell.Changes, *manifest.Package, error) {
task := l.Task(pkg.Reference.String())
if pkg.Reference.IsChannel() {
err := e.state.UpgradeChannel(task, pkg)
return nil, nil, errors.WithStack(err)
}
return e.upgradeVersion(l, pkg)
}
// ResolveLink returns the package for a hermit bin dir link.
//
// Link chains are in the form
//
// <binary> -> <pkg>-<version>.pkg -> hermit
func (e *Env) ResolveLink(l *ui.UI, executable string) (pkg *manifest.Package, binary string, err error) {
links, err := util.ResolveSymlinks(executable)
if err != nil {
return nil, "", errors.WithStack(err)
}
var (
link string
found bool
)
for _, link = range links {
if strings.HasSuffix(link, ".pkg") {
found = true
break
}
binary = link
}
if !found {
return nil, "", errors.Errorf("%s: could not find Hermit .pkg in symlink chain", executable)
}
ref := e.referenceFromBinLink(link)
pkg, err = e.Resolve(l, manifest.ExactSelector(ref), true)
if err != nil {
return nil, "", errors.WithStack(err)
}
return pkg, binary, nil
}
// Exec the specified binary from the given package, replacing this process.
//
// "args" should be os.Args (or equivalent), including the binary name.
// "deps" contains all packages that need to be in the system for the execution.
//
// The missing dependencies are downloaded and unpacked.
func (e *Env) Exec(l *ui.UI, pkg *manifest.Package, binary string, args []string, deps map[string]*manifest.Package) error {
b := l.Task(pkg.Reference.String())
timer := ui.LogElapsed(l, "exec")
err := e.state.CacheAndUnpack(l.Task(pkg.Reference.String()), pkg)
if err != nil {
return errors.WithStack(err)
}
for _, dep := range deps {
if dep.Reference.Compare(pkg.Reference) == 0 {
continue
}
err := e.state.CacheAndUnpack(l.Task(dep.Reference.String()), dep)
if err != nil {
return errors.WithStack(err)
}
}
pkg, err = e.Resolve(l, manifest.ExactSelector(pkg.Reference), true)
if err != nil {
return errors.WithStack(err)
}
if err := e.EnsureChannelIsUpToDate(l, pkg); err != nil {
return errors.WithStack(err)
}
runtimeDeps, err := e.ensureRuntimeDepsPresent(l, pkg)
if err != nil {
return errors.WithStack(err)
}
binaries, err := pkg.ResolveBinaries()
if err != nil {
return errors.WithStack(err)
}
installed, err := e.ListInstalled(l)
if err != nil {
return errors.WithStack(err)
}
ops := e.allEnvarOpsForPackages(runtimeDeps, pkg, installed...)
packageHermitBin, err := e.getPackageRuntimeEnvops(pkg)
if err != nil {
return errors.WithStack(err)
}
if packageHermitBin != nil {
ops = append(ops, packageHermitBin)
}
env := e.envarsFromOps(true, ops)
if err != nil {
return errors.WithStack(err)
}
for _, bin := range binaries {
if filepath.Base(bin) != filepath.Base(binary) {
continue
}
argsCopy := make([]string, len(args))
copy(argsCopy, args)
argsCopy[0] = bin
b.Tracef("exec %s", shellquote.Join(argsCopy...))
l.Clear()
timer()
err = syscall.Exec(bin, argsCopy, env)
return errors.Wrapf(err, "%s: failed to execute %q", pkg, bin)
}
return errors.Errorf("%s: could not find binary %q", pkg, binary)
}
func (e *Env) getPackageRuntimeEnvops(pkg *manifest.Package) (envars.Op, error) {
// If the package contains a Hermit env, add that to the PATH for runtime dependencies
pkgEnvInfo, err := LoadEnvInfo(pkg.Root)
if err != nil {
return nil, errors.WithStack(err)
}
pkgEnv, err := OpenEnv(pkgEnvInfo, e.state, e.packageSource, nil, e.httpClient, e.scriptSums)
if err != nil {
return nil, errors.WithStack(err)
}
if err = pkgEnv.Verify(); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return nil, errors.WithStack(err)
}
return nil, nil
}
return &envars.Prepend{Name: "PATH", Value: pkgEnv.binDir}, nil
}
// Resolve package reference.
//
// If "syncOnMissing" is true, sources will be synced if the selector cannot
// be initially resolved, then resolve attempted again.
func (e *Env) Resolve(l *ui.UI, selector manifest.Selector, syncOnMissing bool) (*manifest.Package, error) {
resolver, err := e.resolver(l)
if err != nil {
return nil, errors.WithStack(err)
}
resolved, err := resolver.Resolve(l, selector)
// If the package is missing sync sources and try again, once.
if syncOnMissing && errors.Is(err, manifest.ErrUnknownPackage) {
if err = resolver.Sync(l, true); err != nil {
return nil, errors.WithStack(err)
}
resolved, err = resolver.Resolve(l, selector)
}
if err != nil {
return nil, errors.WithStack(err)
}
e.readPackageState(resolved)
return resolved, nil
}
// ValidationOptions for manifest validation
type ValidationOptions struct {
// CheckSources if true, check that the package sources are reachable
CheckSources bool
}
// ValidateManifest with given name.
//
// Returns the resolution errors for core systems as warnings.
// If a version fails to resolve for all systems, returns an error.
func (e *Env) ValidateManifest(l *ui.UI, name string, options *ValidationOptions) ([]string, error) {
sources, err := e.sources(l)
if err != nil {
return nil, errors.WithStack(err)
}
mnf, err := manifest.NewLoader(sources).Load(l, name)
if err != nil {
return nil, errors.WithStack(err)
}
refs := mnf.References(name)
var warnings []string
task := l.Task("validate")
for _, ref := range refs {
task.Infof("Validating %s", ref)
w, err := e.validateReference(l, sources, ref, options)
if err != nil {
return nil, errors.WithStack(err)
}
warnings = append(warnings, w...)
}
return warnings, nil
}
func (e *Env) validateReference(l *ui.UI, srcs *sources.Sources, ref manifest.Reference, options *ValidationOptions) ([]string, error) {
var fails []string
var warnings []string
for _, p := range platform.Core {
resolver, err := manifest.New(srcs, manifest.Config{
Env: e.envDir,
State: e.state.Root(),
Platform: platform.Platform{
OS: p.OS,
Arch: p.Arch,
},
})
if err != nil {
return nil, errors.WithStack(err)
}
pkg, err := resolver.Resolve(l, manifest.ExactSelector(ref))
if err != nil {
msg := fmt.Sprintf("%s: %s", p, err.Error())
fails = append(fails, msg)
warnings = append(warnings, msg)
continue
}
if options.CheckSources {
if err := manifest.ValidatePackageSource(e.packageSource, e.httpClient, pkg.Source); err != nil {
return nil, errors.Wrapf(err, "%s: %s", ref, p)
}
}
warnings = append(warnings, pkg.Warnings...)
}
if len(fails) >= len(platform.Core) {
return nil, errors.Errorf("%s failed to resolve on all platforms: %s", ref, strings.Join(fails, "; "))
}
return warnings, nil
}
// ResolveVirtual references to concrete packages.
func (e *Env) ResolveVirtual(l *ui.UI, name string) ([]*manifest.Package, error) {
resolver, err := e.resolver(l)
if err != nil {
return nil, errors.WithStack(err)
}
resolved, err := resolver.ResolveVirtual(name)
if err != nil {
return nil, errors.WithStack(err)
}
for _, pkg := range resolved {
e.readPackageState(pkg)
}
return resolved, nil
}
// UpdateUsage updates the package usage time stamps in the underlying database.
// if the package was not previously present, it is inserted to the DB.
func (e *Env) UpdateUsage(pkg *manifest.Package) error {
err := e.state.WritePackageState(pkg)
if err != nil {
return errors.WithStack(err)
}
return nil
}
// ListInstalledReferences from this environment.
//
// This function is much faster than ListInstalled, if all you need is the Reference.
func (e *Env) ListInstalledReferences() ([]manifest.Reference, error) {
matches, err := filepath.Glob(filepath.Join(e.binDir, ".*.pkg"))
if err != nil {
return nil, errors.WithStack(err)
}
sort.Strings(matches)
out := []manifest.Reference{}
for _, pkgLink := range matches {
ref := e.referenceFromBinLink(pkgLink)
out = append(out, ref)
}
return out, nil
}
// ListInstalled packages from this environment.
func (e *Env) ListInstalled(l *ui.UI) ([]*manifest.Package, error) {
refs, err := e.ListInstalledReferences()
if err != nil {
return nil, errors.WithStack(err)
}
out := []*manifest.Package{}
for _, ref := range refs {
pkg, err := e.Resolve(l, manifest.ExactSelector(ref), false)
if err != nil { // We don't want to error if there are corrupt packages.
continue
}
out = append(out, pkg)
}
return out, nil
}
// Envars returns the fully expanded envars for this environment.
//
// PATH, HERMIT_BIN and HERMIT_ENV will always be explicitly set, plus all