Last active
February 22, 2024 13:46
-
-
Save imaami/d709a4ad05d007854ae13c96f1919ff2 to your computer and use it in GitHub Desktop.
Use ChatGPT to document your C/C++ code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# IMPORTANT: The HTTP authorization header must be found | |
# in ~/.openai in full, not just the API key. | |
# | |
# Usage: ./documentarist.sh /path/file.c "my_function()" | |
# | |
# Requirements: dos2unix, cpp, clang-format, jq, curl | |
# | |
[[ -f "$1" && "$2" ]] && name="${1##*/}" && | |
tmp="$(mktemp -d)" && [[ -d "$tmp" ]] || exit 1 | |
src="$tmp/$name"; dos2unix < "$1" | | |
cpp -fpreprocessed -dD -P -o- 2>/dev/null | | |
clang-format --style='{BasedOnStyle: webkit, | |
IndentWidth: 8, | |
TabWidth: 8, | |
UseTab: ForIndentation}' > "$src" | |
[[ -f "$src" ]] || { rm -fr "$tmp"; exit 1; } | |
fn="\`$(sed -E 's/([[:blank:]]*\.)?[[:blank:]]*$//' <<< "$2")\`." | |
jq --rawfile source <( | |
printf '```\n/** @file %s\n */\n' "$name" | |
cat "$src" | |
printf '\n```' | |
) -Mnc --rawfile system <(cat << \EOF | |
You document C/C++ code using Doxygen syntax. You are shown code and are instructed which function to document. Generate the documentation for this function, but do not include the full function body in your output, just the declaration. | |
To be clear: you read a function definition, but you print only the function declaration with documentation added on top. For example | |
``` | |
int foo (int *bar) { | |
*bar *= 9; | |
return *bar ^ ~0; | |
} | |
``` | |
might become | |
``` | |
/** | |
* @brief Toggle bar. | |
* @param bar The bar to modify. | |
* @return Result status. | |
* @retval 0 no error. | |
* @retval EFAULT @p bar is an invalid address. | |
*/ | |
int foo (int *bar); | |
``` | |
Important points: | |
- There is no function body in the output. Output stops after the argument list's closing parenthesis and a semicolon. This matters because your output will be placed in header files. | |
- Each "@retval" describes one possible return value, no more. Add multiple "@retval" lines if necessary. | |
- "@retval" does not exclude "@return". | |
EOF | |
) '{ | |
"model": "gpt-3.5-turbo-16k", | |
"stream": false, | |
"messages": [ | |
{"role":"system","content":$system}, | |
{"role":"user","content":$source}, | |
{"role":"user","content":"Document '"${fn//\"/\\\"}"'"} | |
] | |
}' \ | |
| curl https://api.openai.com/v1/chat/completions -s -S -d @- \ | |
-H @"$HOME/.openai" -H Content-Type:\ application/json \ | |
| jq -r '.choices[0].message.content' | |
rm -fr "$tmp" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment