llm scaffold | llm scaffold | generate code | Search

The code imports various modules and defines a function called generateBash which generates shell code using a Large Language Model (LLM) and saves it to a GitHub repository. The function checks the repository's existence, updates it if necessary, extracts code blocks from the LLM's response, and writes them to a new file in the repository.

Run example

npm run import -- "bash project files"

bash project files


const fs = require('fs')
const path = require('path')
const PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE || '';
const {spawnSync} = require('child_process')
const {safeurl} = importer.import("domain cache tools")

async function generateBash(prompt, github) {
  const llmCode = await importer.import("llm code")

  // TODO: local pull
  if(!fs.existsSync(github)
    && fs.existsSync(path.join(PROFILE_PATH, github))) {
      github = path.join(PROFILE_PATH, github)
  }

  if(github.includes('://')
    && fs.existsSync(path.basename(github).replace('.git', ''))
  ) {
    github = path.join(PROFILE_PATH, path.basename(github).replace('.git', ''))
  }

  if(!fs.existsSync(github)) {
    return
  }

  let baseName = path.basename(github)

  await spawnSync('git', ['pull'], {
    cwd: github,
    timeout: 3000,
    stdio: ['pipe', 'pipe', 'pipe']
  })

  // TODO: generate bash
  let q1 = 'Project listing:\n' +  fs.readdirSync(github).join('\n')
    + '\nGenerate a Bash shell script for the following request, include any empty file touch/folder creations, file moves or general file management: ' + prompt + '\n</think>Don\'t do any file content insertion or reasoning, limit response to two or three shell command lines.'
  console.log('User: ' + q1)
  let a1 = await llmCode(q1)
  console.log('AI: ' + a1)

  // try to extract code blocks
  let code = a1.matchAll(/```(bash|javascript|code)*\n[\s\S]*?\n```/gi)

  // make sure we're oporating on our own directory
  let codeBlocks = '#!/bin/bash\ncd /home/' + baseName + '\n\n'

  // extract code blocks from response
  for(let match of code) {
    codeBlocks += match[0].replace(/^```(bash|javascript|code)*\n|\n```$/gi, '') + '\n'
  }
  if(!codeBlocks) {
    console.log('Error, couldn\'t find code in:' + a1)
    return
  }

  if(!fs.existsSync(path.join(github, '.automations'))) {
    fs.mkdirSync(path.join(github, '.automations'))
  }
  const CODE_FILE = path.join('.automations', safeurl((new Date).toISOString() + '-' + prompt) + '.sh')
  fs.writeFileSync(path.join(github, CODE_FILE), codeBlocks)
  fs.chmodSync(path.join(github, CODE_FILE), 0o777)

  // TODO: execute new docker file on project
  let args = ['run', '-it', '--rm', '-v', 
    // TODO: mount project directory
    github + ':/home/' + baseName, 
    // TODO: change docker image
    'alpine:latest', 'sh', 
    path.join('/home/', baseName, CODE_FILE)]
  console.log('docker', args.join(' '))
  await spawnSync('docker', args, {
    cwd: github,
    timeout: 3000,
    stdio: [0, 1, 2]
  })

  // TODO: git commit and git push?

}

module.exports = generateBash

What the code could have been:

const fs = require('fs');
const path = require('path');
const process = require('process');
const { spawnSync } = require('child_process');
const importer = require('importer');
const safeurl = require('domain-cache-tools').safeurl;

async function generateBash(prompt, github) {
  try {
    const llmCode = await importer.import('llm-code');

    const profilePath = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE || '';
    let githubPath = github;

    if (!fs.existsSync(githubPath) && fs.existsSync(path.join(profilePath, github))) {
      githubPath = path.join(profilePath, github);
    }

    if (githubPath.includes('://') && fs.existsSync(path.basename(githubPath).replace('.git', ''))) {
      githubPath = path.join(profilePath, path.basename(githubPath).replace('.git', ''));
    }

    if (!fs.existsSync(githubPath)) {
      return;
    }

    const baseName = path.basename(githubPath);

    const pullResult = await spawnSync('git', ['pull'], {
      cwd: githubPath,
      timeout: 3000,
      stdio: ['pipe', 'pipe', 'pipe']
    });

    if (pullResult.status!== 0) {
      console.log('Git pull failed with status:', pullResult.status);
      return;
    }

    const promptText = `Project listing:
${fs.readdirSync(githubPath).join('\n\n')}
Generate a Bash shell script for the following request, include any empty file touch/folder creations, file moves or general file management: ${prompt}\nDon't do any file content insertion or reasoning, limit response to two or three shell command lines.`;
    console.log('User:', promptText);

    const response = await llmCode(promptText);
    console.log('AI:', response);

    const codeBlocks = extractCodeBlocks(response);

    if (!codeBlocks) {
      console.log('Error, couldn\'t find code in:', response);
      return;
    }

    const codeFile = path.join('.automations', safeurl(new Date().toISOString() + '-' + prompt) + '.sh');
    fs.writeFileSync(path.join(githubPath, codeFile), codeBlocks);
    fs.chmodSync(path.join(githubPath, codeFile), 0o777);

    const dockerArgs = [
      'run',
      '-it',
      '--rm',
      '-v',
      `${githubPath}:/${baseName}`,
      'alpine:latest',
     'sh',
      `/${baseName}/${codeFile}`
    ];

    const dockerResult = await spawnSync('docker', dockerArgs, {
      cwd: githubPath,
      timeout: 3000,
      stdio: [0, 1, 2]
    });

    if (dockerResult.status!== 0) {
      console.log('Docker run failed with status:', dockerResult.status);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

function extractCodeBlocks(response) {
  const codeBlocks = response.matchAll(/```(bash|javascript|code)*\n[\s\S]*?\n```/gi);
  let blocks = '';

  for (const match of codeBlocks) {
    blocks += match[0].replace(/^```(bash|javascript|code)*\n|\n```$/gi, '') + '\n';
  }

  return blocks;
}

module.exports = generateBash;

Code Breakdown

Import Statements

generateBash Function