rogpeppe / go-internal

Selected Go-internal packages factored out from the standard library
BSD 3-Clause "New" or "Revised" License
876 stars 77 forks source link

Question: Is it possible to store `stdout` for later in `testscript`? #274

Closed williammartin closed 1 month ago

williammartin commented 1 month ago

Question

I'm exploring a test script that looks like:

# Use gh as a credential helper
exec gh auth setup-git

# Create a repository with a file so it has a default branch
exec gh repo create $ORG/$SCRIPT_NAME-$RANDOM_STRING --add-readme --private

# Defer repo cleanup
defer gh repo delete --yes $ORG/$SCRIPT_NAME-$RANDOM_STRING

# Clone the repo
exec gh repo clone $ORG/$SCRIPT_NAME-$RANDOM_STRING

# Prepare a branch to PR
cd $SCRIPT_NAME-$RANDOM_STRING
exec git checkout -b feature-branch
exec git commit --allow-empty -m 'Empty Commit'
exec git push -u origin feature-branch

# Create the PR
exec gh pr create --title 'Feature Title' --body 'Feature Body'

# View the PR
exec gh pr view 1
stdout 'Feature Title'

You can see in the final section I hard code a 1, indicating the Pull Request created has number 1. However, a more robust way to approach this in case of future parallelism would be to store the stdout of the previous command (which outputs the URL of the newly created PR).

I know that there is a stdin stdout incantation but this doesn't quite work when:

I had a look at the implementation for env but it doesn't seem to provide the same capability as stdin.

Perhaps the best thing for me to do is write a custom command but I guess I need to explore what is available in there. Am I missing something? Thanks!

mvdan commented 1 month ago

you can cp stdout some-file-path, if that's what you mean.

williammartin commented 1 month ago

Thanks for the quick response. It's not quite what I meant but maybe I can use it to achieve the same thing?

Is there an inbuilt mechanism for getting the contents of a file into something that can be passed as an argument to a command?

mvdan commented 1 month ago

Not out of the box, but doing a "read file into env var" command is trivial: https://github.com/burrowers/garble/blob/48dd2263a90b67a2d3997f5b3b1b7cf537a35ea1/main_test.go#L142

williammartin commented 1 month ago

Heh, yeh that's pretty much what I ended up writing as stdout2env just now. Thanks very much for your help!

mvdan commented 1 month ago

Arguably it could be provided out of the box, but there's a balance to be struck with bloating the API and docs with features :) In this case it is sometimes useful, but it is really a one-line function, so I think it's fine to leave out.

williammartin commented 1 month ago

Totally understand. Mainly I just wondered if I was missing an obvious solution and I hadn't initially clocked that ts.ReadFile handled the stdio cases.