Generate code for any language, with any language.

gocog - generate code for any language, with any language

gocog v1.0 build 20130206

Binaries for popular OSes are available on the Downloads page of the wiki

If you don't want to work on the sourcecode, you can just download a binary for gocog and use it for your own project. They require no installation and have no prerequisites. Copy and go.

Design of gocog is heavily based on cog.py. Many thanks to Ned Batchelder for a really great design.

Usage:
  gocog [OPTIONS] [INFILE | @FILELIST] ...

  Runs gocog over each infile. 
  Strings prepended with @ are assumed to be files continaing newline delimited lists of gocog command lines.
  Command line options are passed to each command line in the file list, but options on the file list line
  will override command line options. You may have filelists specified inside filelist files.

Help Options:
  -h, --help         Show this help message

Application Options:
  -z, --eof          The end marker can be assumed at eof.
  -v, --verbose      enables verbose output
  -q, --quiet        turns off all output
  -S, --serial       Write to the specified cog files serially
  -c, --cmd          The command used to run the generator code (go)
  -a, --args         Comma separated arguments to cmd, %s for the code file
                     ([run, %s])
  -e, --ext          Extension to append to the generator filename (.go)
  -M, --startmark    String that starts gocog statements ([[[)
  -E, --endmark      String that ends gocog statements (]]])
  -x, --excise       Excise all the generated output without running the
                     generators.
  -V, --version      Display the version of gocog

How it works

gocog is a command line executable that processes in-line code in a file and outputs the results into the same file.

Code is embedded in comments in the given files, delimited thusly:

[[[gocog
  <generator code that will be run to generate output>
gocog]]]
[[[end]]]

Anything written to standard out from the generator code will be injected between gocog]]] and [[[end]]]

The generator code embedded in the file is written out to a temporary file on disk by gocog named filename_cog.ext (where filename is the original filename, and ext is the appropriate extension for the generator language. This file is then run using the specified command line tool. Standard output generated by the generator code is piped to a new file named filename_cog, along with the original text. If generation is successful for all gocog blocks in a file, this output file is then used to replace the original file.

If at any time there is an error while running gocog over a file, the original file is not replaced. Errors from the generator code will be piped to gocog's stderr.

By default, each file is processed in parallel, to speed the processing of large numbers of files.

The gocog marker tags can be preceded by any text (such as comment tags to prevent your compiler/interpreter from barfing on them).

Any non-whitespace text that precedes the gocog start mark will be treated as a single line comment tag and will be removed in the generator code that is written out - for example:

# [[[gocog
# do something here
#     and some indent
# gocog]]]
# [[[end]]]

output code (this is what will be written to a file and run by your favorite language):

do something here
    and some indent

You can rerun gocog over the same file multiple times. Previously generated text will be discarded and replaced by the newly generated text.

You can have multiple blocks of gocog generator code inside the same file.

Any filename prepended with the '@' symbol in the command line will be opened and read, with each line assumed to be a gocog command line. In this way you can run different command lines over different files, even using different languages to generate code in each file. Check out files.txt for an example. This is the file that gocog uses to generate code for itself.

You can include other @files inside an @file, and those will also be opened and read the same way.

Examples

Check out the Examples page of the wiki for real world projects using gocog, including a description of how gocog uses gocog.

Now for a toy example: Using generator code written in Go to write out properties for a C# class

using System;

namespace foo 
{
  public class Foo
  {
    /* [[[gocog
    package main
    import "fmt"
    func main() {
      for _, s := range []string{ "Bar", "Baz", "Bat", "Stuff" } {
        fmt.Printf("\t\tpublic String %s { get; set; }\n", s)
      }
    }
    gocog]]]  */
    // [[[end]]]
  }
}

Output:

using System;

namespace foo 
{
  public class Foo
  {
    /* [[[gocog
    package main
    import "fmt"
    func main() {
      for _, s := range []string{ "Bar", "Baz", "Bat", "Stuff" } {
        fmt.Printf("\t\tpublic String %s { get; set; }\n", s)
      }
    }
    gocog]]]  */
    public String Bar { get; set; }
    public String Baz { get; set; }
    public String Bat { get; set; }
    public String Stuff { get; set; }
    // [[[end]]]
  }
}

Things to note: The generator code and gocog markers are all hidden from the original file's compiler by comments, so the file is always valid.

The generator code stays in the file even after running through gocog. This keeps the generator code and the target close together so there's no need to worry about one getting lost. It also makes it a lot more clear where and how the output will be used in the original file.

Building gocog

  • just run go build or go install like a normal go package.
  • To pick up any updates to the usage text in the documentation, and to add today's date to the version number, run go install and then gocog @files.txt from the root code directory.
  • The binaries posted on the wiki are generated using Dave Cheney's go cross compile scripts which I won't go into how to use here.

Build Status

Owner
Nate Finch
Author of gorram, lumberjack, pie, gnorm, mage, and others. https://twitter.com/natethefinch
Nate Finch
Similar Resources

AI-powered code snippet generator using ChatGPT. Generate code in various languages based on natural language descriptions!

SnipForge - AI-Powered Code Snippet Generator SnipForge is a powerful command-line interface (CLI) tool that utilizes OpenAI's GPT technology to gener

May 5, 2023

🐢 Automated code review tool integrated with any code analysis tools regardless of programming language

🐢 Automated code review tool integrated with any code analysis tools regardless of programming language

reviewdog - A code review dog who keeps your codebase healthy. reviewdog provides a way to post review comments to code hosting service, such as GitHu

Jan 2, 2023

🐢 Automated code review tool integrated with any code analysis tools regardless of programming language

🐢 Automated code review tool integrated with any code analysis tools regardless of programming language

reviewdog - A code review dog who keeps your codebase healthy. reviewdog provides a way to post review comments to code hosting service, such as GitHu

Jan 7, 2023

Handle any SQS use case, monitor any queue. Reusable for any project! Invoke in a goroutine to process SQS messages.

GOSQS This package is intended to be a Go SQS listener that can be imported and invoked as a goroutine handled by the life cycle of your service. It's

Dec 22, 2021

Go code to generate Captcha letters for any TrueType font format files.

Go code to generate Captcha letters for any TrueType font format files. The code can be modified for the background and font colors. The code can be easily upgraded for distorted and rotated letters. These generated lettes can be stiched together to make captcha string.

Jan 31, 2022

Floppa programming language inspired by the brainf*ck programming language. Created just for fun and you can convert your brainf*ck code to floppa code.

Floppa Programming Language Created just for fun. But if you want to contribute, why not? Floppa p.l. inspired by the brainf*ck programming language.

Oct 20, 2022

A Golang tool that does static analysis, unit testing, code review and generate code quality report.

A Golang tool that does static analysis, unit testing, code review and generate code quality report.

goreporter A Golang tool that does static analysis, unit testing, code review and generate code quality report. This is a tool that concurrently runs

Jan 8, 2023

Test your code without writing mocks with ephemeral Docker containers πŸ“¦ Setup popular services with just a couple lines of code ⏱️ No bash, no yaml, only code πŸ’»

Gnomock – tests without mocks πŸ—οΈ Spin up entire dependency stack 🎁 Setup initial dependency state – easily! 🏭 Test against actual, close to product

Dec 29, 2022

:triangular_ruler:gofmtmd formats go source code block in Markdown. detects fenced code & formats code using gofmt.

:triangular_ruler:gofmtmd formats go source code block in Markdown. detects fenced code & formats code using gofmt.

gofmtmd gofmtmd formats go source code block in Markdown. detects fenced code & formats code using gofmt. Installation $ go get github.com/po3rin/gofm

Oct 31, 2022

octocov is a tool for collecting code metrics (code coverage, code to test ratio and test execution time).

octocov is a tool for collecting code metrics (code coverage, code to test ratio and test execution time).

Jan 9, 2023

sail is an operation framework based on Ansible/Helm. sail follows the principles of Infrastructure as Code (IaC), Operation as Code (OaC), and Everything as Code. So it is a tool for DevOps.

sail δΈ­ζ–‡ζ–‡ζ‘£ sail is an operation framework based on Ansible/Helm. sail follows the principles of Infrastructure as Code (IaC), Operation as Code (OaC),a

Dec 16, 2021

Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

Advent of Code 2021 Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved

Dec 2, 2021

Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like. This repository holds my submission/answers for these challenges.

Advent of Code - Zach Howell's Answers Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels

Jan 4, 2022

This is the code example how to use SQL to query data from any relational databases in Go programming language.

Go with SQL example This is the code example how to use SQL to query data from any relational databases in Go programming language. To start, please m

Mar 12, 2022

✨ Generate unique IDs (Port of Node package "generate-snowflake" to Golang)

✨ Generate Snowflake Generate unique IDs. Inspired by Twitter's Snowflake system. πŸ“¦ Installation Initialize your project (go mod init example.com/exa

Feb 11, 2022

Go code for PostgreSQL. A Go language code which connects to PostgreSQL database for CRUD operation

Go code for PostgreSQL. A Go language code which connects to PostgreSQL database for CRUD operation

Jan 25, 2022

Generate Crossplane Providers from any Terraform Provider

Terrajet - Generate Crossplane Providers from any Terraform Provider Terrajet is a code generator framework that allows developers to build code gener

Dec 29, 2022

Generate an interactive, autocompleting shell for any Cobra CLI

Generate an interactive, autocompleting shell for any Cobra CLI

cobra-shell Description Leverages the Cobra completion API to generate an interactive shell for any Cobra CLI, powered by go-prompt. On-the-fly autoco

Dec 19, 2022

A tool to build, deploy, and release any application on any platform.

A tool to build, deploy, and release any application on any platform.

Waypoint Website: https://www.waypointproject.io Tutorials: HashiCorp Learn Forum: Discuss Waypoint allows developers to define their application buil

Dec 28, 2022
Automatically generate RESTful API documentation with Swagger 2.0 for Go.
Automatically generate RESTful API documentation with Swagger 2.0 for Go.

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

Jan 9, 2023
A program to build, run, and restart a Go program on code change

devrun A program to build, run, and restart a Go program on code change. It also supports watching all your Go imports too. So if you change the code

Apr 4, 2022
Yet another Go REPL that works nicely. Featured with line editing, code completion, and more.
  Yet another Go REPL that works nicely. Featured with line editing, code completion, and more.

gore Yet another Go REPL that works nicely. Featured with line editing, code completion, and more. (Screencast taken with cho45/KeyCast) Usage gore Af

Jan 2, 2023
Will autobuild and kill/relaunch the target when you update the code.

Use like rerun github.com/skelterjohn/go.uik/uiktest Usage: rerun [--test] [--build] [--race] [--no-run] <import path> [arg]* For any go executable in

Jul 23, 2022
Go package for syntax highlighting of code

syntaxhighlight Package syntaxhighlight provides syntax highlighting for code. It currently uses a language-independent lexer and performs decently on

Nov 18, 2022
πŸ”₯ Continuous profiling platform β€” debug performance issues in your code!
πŸ”₯  Continuous profiling platform β€” debug performance issues in your code!

Pyroscope is an open source continuous profiling platform.

Jan 7, 2023
A tool that helps you write code in your favorite IDE: your word processor!
A tool that helps you write code in your favorite IDE: your word processor!

WordIDE Have you ever wondered: How would it feel like to write code in a word processor? Me neither. But after months minutes of planning, I present

Jul 21, 2022
Simple tool that updates Visual Studio Code workspace(s) to include Go modules in gopath/src, then launches VSCode if only one modified.

Simple tool that updates Visual Studio Code workspace(s) to include Go modules in gopath/src, then launches VSCode if only one modified.

Jan 27, 2022
LuaHelper is a High-performance lua plugin, Language Server Protocol for lua.
LuaHelper is a High-performance lua plugin, Language Server Protocol for lua.

LuaHelper is a High-performance lua plugin, Language Server Protocol for lua.

Dec 29, 2022
Pulumi - Modern Infrastructure as Code. Any cloud, any language πŸš€
Pulumi - Modern Infrastructure as Code. Any cloud, any language πŸš€

Pulumi's Infrastructure as Code SDK is the easiest way to create and deploy cloud software that use containers, serverless functions, hosted services,

Dec 30, 2022