meta-automata-nix / actions-batch

Time-sharing supercomputer built on GitHub Actions
https://blog.alexellis.io/github-actions-timesharing-supercomputer/
MIT License
1 stars 0 forks source link

Sweep: Please add comments to your code, and while we're at it; #7

Closed ar4s-gh closed 4 months ago

ar4s-gh commented 4 months ago

Please add comments to your code, and while we're at it;

Make a sweep.yml with rule that reminds you to Comment your code like divnix/std (github repo) when writing or using Nix?.

Originally posted by @ar4s-gh in https://github.com/ar4s-gh/actions-batch/issues/1#issuecomment-2067790695

sweep-ai[bot] commented 4 months ago
Sweeping

75%

Actions

main.go

Add comments to the `main()` function to explain the high-level flow and purpose of the program.
--- 
+++ 
@@ -1,5 +1,5 @@
 func main() {
-
+   // Define command-line flags for configuring the program's behavior
    var (
        owner                string
        fileName             string
@@ -16,6 +16,7 @@
        artifactsPath        string
    )

+   // Parse command-line flags
    flag.StringVar(&owner, "owner", "actuated-samples", "The owner of the GitHub repository")
    flag.StringVar(&fileName, "file", "", "The name of the file to run via a GitHub Action")
    flag.StringVar(&tokenFile, "token-file", "", "The name of the PAT token file")
@@ -30,4 +31,6 @@
    flag.BoolVar(&verbose, "verbose", false, "Verbose logging")
    flag.StringVar(&artifactsPath, "out", "", "Path to use to unzip the artifacts folder from the build, if there is one")

-   flag.Parse()
+   flag.Parse()
+
+   // Rest of main() function...

main.go

Add comments to the `downloadArtifacts()` function to explain its purpose and how it works.
--- 
+++ 
@@ -1,4 +1,10 @@
+// downloadArtifacts downloads and extracts the artifacts generated by a GitHub Actions workflow run.
+// It takes a context, GitHub client, repository owner and name, workflow run ID, and optional output path.
+// The function lists the artifacts for the given workflow run, downloads each one, extracts it to a temporary
+// directory, and optionally moves it to the specified output path. It then prints a summary of the extracted
+// artifact files and their sizes.
 func downloadArtifacts(ctx context.Context, client *github.Client, owner, repoName string, wfID int64, artifactsPath string) error {
+   // List the artifacts for the given workflow run
    artifacts, _, err := client.Actions.ListWorkflowRunArtifacts(ctx, owner, repoName, wfID, &github.ListOptions{
        PerPage: 100,
    })
@@ -6,7 +12,9 @@
        return err
    }

+   // Iterate over each artifact
    for _, a := range artifacts.Artifacts {
+       // Get the download URL for the artifact
        dlUrl, dlUrlRes, err := client.Actions.DownloadArtifact(ctx, owner, repoName, a.GetID(), 1)
        if err != nil {
            return err
@@ -20,6 +28,7 @@
            return fmt.Errorf("failed to get download URL with status: %d", dlUrlRes.StatusCode)
        }

+       // Create a new HTTP request to download the artifact
        req, err := http.NewRequest(http.MethodGet, dlUrl.String(), nil)
        if err != nil {
            return err
@@ -27,6 +36,7 @@
        req.Header.Set("Accept", "application/vnd.github.v3+json")
        req.Header.Set("User-Agent", "actuated-batch")

+       // Send the request and get the response
        res, err := http.DefaultClient.Do(req)
        if err != nil {
            return err
@@ -42,31 +52,37 @@
            return fmt.Errorf("failed to get logs with status: %d, body: %s", res.StatusCode, string(body))
        }

+       // Create a temporary file to store the downloaded artifact
        tmp := os.TempDir()
        tmpFile, err := os.CreateTemp(tmp, a.GetName())
        if err != nil {
            return err
        }

+       // Copy the artifact contents to the temporary file
        if _, err := io.Copy(tmpFile, res.Body); err != nil {
            return err
        }

+       // Determine the output path for the extracted artifact
        outPath := ""
        if len(artifactsPath) > 0 {
            outPath = artifactsPath
        }

+       // Extract the artifact to the output path
        artifactsPath, err := unzipArtifacts(tmpFile.Name(), outPath)
        if err != nil {
            return err
        }

+       // Read the contents of the extracted artifact directory
        artifactsDir, err := os.ReadDir(artifactsPath)
        if err != nil {
            return err
        }

+       // Print a summary of the extracted artifact files and their sizes
        fmt.Printf("Contents of: %s\n\n", artifactsPath)
        t := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.TabIndent)
        fmt.Fprintf(t, "FILE\tSIZE\n")

main.go

Add comments to the `unzipArtifacts()` function to explain its purpose and how it works.
--- 
+++ 
@@ -1,9 +1,17 @@
+// unzipArtifacts extracts the contents of a zip file to a target directory.
+// It takes the path to the zip file and an optional output path. If no output
+// path is specified, a temporary directory is created.
+// The function opens the zip file, determines its size, and then calls the
+// Unzip function to extract its contents to the target directory.
+// It returns the path to the extracted contents.
 func unzipArtifacts(target, outPath string) (string, error) {

+   // Determine the target path for extraction
    targetPath := ""
    if len(outPath) > 0 {
        targetPath = outPath
    } else {
+       // Create a temporary directory if no output path is specified
        tmp := os.TempDir()
        tmpPath, err := os.MkdirTemp(tmp, "artifacts-*")
        if err != nil {
@@ -12,17 +20,20 @@
        targetPath = tmpPath
    }

+   // Open the zip file
    f, err := os.Open(target)
    if err != nil {
        return "", fmt.Errorf("failed to open file: %w", err)
    }
    defer f.Close()

+   // Get the size of the zip file
    stat, err := f.Stat()
    if err != nil {
        return "", fmt.Errorf("failed to stat file: %w", err)
    }

+   // Extract the contents of the zip file to the target directory
    if err := Unzip(f, stat.Size(), targetPath, quietUnzip); err != nil {
        return "", fmt.Errorf("failed to unzip file: %w", err)
    }

main.go

Add comments to the `getLogs()` function to explain its purpose and how it works.
--- 
+++ 
@@ -1,6 +1,13 @@
+// getLogs retrieves the logs for a GitHub Actions workflow run.
+// It takes the URL of the logs as input, creates a new HTTP request with the
+// appropriate headers, sends the request, and returns the response body as
+// a byte slice.
+// If the request fails or the response status code is not 200 OK, an error
+// is returned.
 func getLogs(logsURL *url.URL) ([]byte, error) {
    fmt.Printf("Getting logs from %s\n", logsURL.String())

+   // Create a new HTTP request
    req, err := http.NewRequest(http.MethodGet, logsURL.String(), nil)
    if err != nil {
        return []byte{}, err
@@ -8,6 +15,7 @@
    req.Header.Set("Accept", "application/vnd.github.v3+json")
    req.Header.Set("User-Agent", "actuated-batch")

+   // Send the request and get the response
    res, err := http.DefaultClient.Do(req)
    if err != nil {
        return []byte{}, err
@@ -17,13 +25,14 @@
    if res.Body != nil {
        defer res.Body.Close()

+       // Read the response body
        body, _ = io.ReadAll(res.Body)
    }

+   // Check the response status code
    if res.StatusCode != http.StatusOK {
        return []byte{}, fmt.Errorf("failed to get logs, %s", string(body))
    }

    return body, nil
-
 }

sweep.yml

Create a new file named `sweep.yml` to store a rule that reminds the developer to comment their code.
rules:
  comment_code:
    description: |
      Reminds the developer to add comments to their code to improve readability and maintainability.

      Code should be commented in a similar style to the divnix/std GitHub repository when writing 
      or using Nix: https://github.com/divnix/std
    include:
      - "**/*.go"
    exclude:
      - "**/vendor/**"
    condition:
      type: script
      script: |
        function hasComments(file) {
          const content = file.getContent();
          const lines = content.split('\n');
          const commentRegex = /^\s*\/\//;

          let commentCount = 0;
          for (const line of lines) {
            if (commentRegex.test(line)) {
              commentCount++;
            }
          }

          const commentRatio = commentCount / lines.length;
          return commentRatio >= 0.1; // Require at least 10% of lines to have comments
        }

        hasComments(file);
    pass:
      - "Code is well-commented"
    fail:
      - "Please add more comments to your code to improve readability and maintainability"
      - "Refer to the divnix/std repository for examples of good commenting practices: https://github.com/divnix/std"

Feel free to add more details to the issue description so Sweep can better address it. Alternatively, reach out to Kevin or William for help at https://community.sweep.dev/.

For bonus Sweep issues, please report this bug on our community forum (tracking ID: bacc7e95ab).


[!TIP] To recreate the pull request, edit the issue title or description.

This is an automated message generated by Sweep AI.

ar4s-gh commented 4 months ago

That's actually great commenting! Please always have artifacts put in the "/uploads" directory. You can read the README.MD for instructions.