(ctx context.Context, rep repo.Repository)
| 42 | } |
| 43 | |
| 44 | func (c *commandPolicyExport) run(ctx context.Context, rep repo.Repository) error { |
| 45 | output, err := getOutput(c) |
| 46 | if err != nil { |
| 47 | return err |
| 48 | } |
| 49 | |
| 50 | if file, ok := output.(*os.File); ok { |
| 51 | defer func() { |
| 52 | err = stderrors.Join(err, file.Close()) |
| 53 | }() |
| 54 | } |
| 55 | |
| 56 | policies := make(map[string]*policy.Policy) |
| 57 | |
| 58 | if c.global || len(c.targets) > 0 { |
| 59 | targets, err := c.policyTargets(ctx, rep) |
| 60 | if err != nil { |
| 61 | return err |
| 62 | } |
| 63 | |
| 64 | for _, target := range targets { |
| 65 | definedPolicy, err := policy.GetDefinedPolicy(ctx, rep, target) |
| 66 | if err != nil { |
| 67 | return errors.Wrapf(err, "can't get defined policy for %q", target) |
| 68 | } |
| 69 | |
| 70 | policies[target.String()] = definedPolicy |
| 71 | } |
| 72 | } else { |
| 73 | ps, err := policy.ListPolicies(ctx, rep) |
| 74 | if err != nil { |
| 75 | return errors.Wrap(err, "failed to list policies") |
| 76 | } |
| 77 | |
| 78 | for _, policy := range ps { |
| 79 | policies[policy.Target().String()] = policy |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | var toWrite []byte |
| 84 | |
| 85 | if c.jsonIndent { |
| 86 | toWrite, err = json.MarshalIndent(policies, "", " ") |
| 87 | } else { |
| 88 | toWrite, err = json.Marshal(policies) |
| 89 | } |
| 90 | |
| 91 | impossible.PanicOnError(err) |
| 92 | |
| 93 | _, err = fmt.Fprintf(output, "%s\n", toWrite) |
| 94 | |
| 95 | return errors.Wrap(err, "unable to write policy to output") |
| 96 | } |
| 97 | |
| 98 | func getOutput(c *commandPolicyExport) (io.Writer, error) { |
| 99 | var err error |
nothing calls this directly
no test coverage detected