ronantakizawa/codereview-bench huggingface dataset:
Repository: nvm-sh/nvm
File: nvm.sh (Shell)

Code before:
  esac

  local KIND
  case "${2-}" in
    binary | source) KIND="${2}" ;;
    *)
      nvm_err 'supported kinds: binary, source'
      return 2
    ;;
  esac

  local VERSION
  VERSION="${3-}"

  local NVM_OS
  NVM_OS="$(nvm_get_os)"

  local NVM_ARCH
  NVM_ARCH="$(nvm_get_arch)"
  if ! nvm_is_merged_node_version "${VERSION}"; then
    if [ "${NVM_ARCH}" = 'armv6l' ] || [ "${NVM_ARCH}" = 'armv7l' ]; then
      NVM_ARCH="arm-pi"
    fi
  fi

  # If node version in below 16.0.0 then there is no arm64 packages available in nod erepositories, so we have to install "x64" arch packages
  # If running MAC M1 :: arm64 ARCH and Darwin OS then use "x64" Architecture because node doesn't provide darwin_arm64 package
  if ! nvm_version_greater_than_or_equal_to "${VERSION}" 16.0.0; then
    if [ "_${NVM_OS}" = '_darwin' ] && [ "${NVM_ARCH}" = 'arm64' ]; then
      NVM_ARCH=x64
    fi
  fi

  if [ "${KIND}" = 'binary' ]; then
    nvm_echo "${FLAVOR}-${VERSION}-${NVM_OS}-${NVM_ARCH}"
  elif [ "${KIND}" = 'source' ]; then
    nvm_echo "${FLAVOR}-${VERSION}"
  fi
}

nvm_get_artifact_compression() {
  local VERSION
  VERSION="${1-}"

  local NVM_OS
  NVM_OS="$(nvm_get_os)"

  local COMPRESSION
  COMPRESSION='tar.gz'
  if [ "_${NVM_OS}" = '_win' ]; then
    COMPRESSION='zip'

Review comment (suggestion):
```suggestion
  # If node version in below 16.0.0 then there is no arm64 packages available in node repositories, so we have to install "x64" arch packages
```

Code after:
  esac

  local KIND
  case "${2-}" in
    binary | source) KIND="${2}" ;;
    *)
      nvm_err 'supported kinds: binary, source'
      return 2
    ;;
  esac

  local VERSION
  VERSION="${3-}"

  local NVM_OS
  NVM_OS="$(nvm_get_os)"

  local NVM_ARCH
  NVM_ARCH="$(nvm_get_arch)"
  if ! nvm_is_merged_node_version "${VERSION}"; then
    if [ "${NVM_ARCH}" = 'armv6l' ] || [ "${NVM_ARCH}" = 'armv7l' ]; then
      NVM_ARCH="arm-pi"
    fi
  fi

  # If node version in below 16.0.0 then there is no arm64 packages available in node repositories, so we have to install "x64" arch packages
  # If running MAC M1 :: arm64 arch and Darwin OS then use "x64" Architecture because node doesn't provide darwin_arm64 package below v16.0.0
  if nvm_version_greater '16.0.0' "${VERSION}"; then
    if [ "_${NVM_OS}" = '_darwin' ] && [ "${NVM_ARCH}" = 'arm64' ]; then
      NVM_ARCH=x64
    fi
  fi

  if [ "${KIND}" = 'binary' ]; then
    nvm_echo "${FLAVOR}-${VERSION}-${NVM_OS}-${NVM_ARCH}"
  elif [ "${KIND}" = 'source' ]; then
    nvm_echo "${FLAVOR}-${VERSION}"
  fi
}

nvm_get_artifact_compression() {
  local VERSION
  VERSION="${1-}"

  local NVM_OS
  NVM_OS="$(nvm_get_os)"

  local COMPRESSION
  COMPRESSION='tar.gz'
  if [ "_${NVM_OS}" = '_win' ]; then
    COMPRESSION='zip'
Repository: nvm-sh/nvm
File: nvm.sh (Shell)

Code before:
  # kernel.
  if [ "_${NVM_OS}" = "_sunos" ]; then
    if HOST_ARCH=$(pkg_info -Q MACHINE_ARCH pkg_install); then
      HOST_ARCH=$(nvm_echo "${HOST_ARCH}" | command tail -1)
    else
      HOST_ARCH=$(isainfo -n)
    fi
  elif [ "_${NVM_OS}" = "_aix" ]; then
    HOST_ARCH=ppc64
  else
    HOST_ARCH="$(command uname -m)"
  fi

  local NVM_ARCH
  case "${HOST_ARCH}" in
    x86_64 | amd64) NVM_ARCH="x64" ;;
    i*86) NVM_ARCH="x86" ;;
    aarch64) NVM_ARCH="arm64" ;;
    *) NVM_ARCH="${HOST_ARCH}" ;;
  esac

  # If running a 64bit ARM kernel but a 32bit ARM userland,
  # change ARCH to 32bit ARM (armv7l) if /sbin/init is 32bit executable
  if [ "$(uname)-${NVM_ARCH}" = "Linux-arm64" ] &&
    L="$(ls -dl /sbin/init 2>/dev/null)" &&
    [ "$(od -An -t x1 -j 4 -N 1 "${L#*-> }")" = ' 01' ]; then
    NVM_ARCH=armv7l
    HOST_ARCH=armv7l
  fi

  nvm_echo "${NVM_ARCH}"
}

nvm_get_minor_version() {
  local VERSION
  VERSION="$1"

  if [ -z "${VERSION}" ]; then
    nvm_err 'a version is required'
    return 1
  fi

  case "${VERSION}" in
    v | .* | *..* | v*[!.0123456789]* | [!v]*[!.0123456789]* | [!v0123456789]* | v[!0123456789]*)
      nvm_err 'invalid version number'
      return 2
    ;;
  esac

  local PREFIXED_VERSION
  PREFIXED_VERSION="$(nvm_format_version "${VERSION}")"

Review comment (suggestion):
i'd rather do this in two checks, just in case one of them has a dash in it.
```suggestion
    if [ "$(uname)" = 'Linux' ] && [ "${NVM_ARCH}" = 'arm64' ] \
      && L="$(ls -dl /sbin/init 2>/dev/null)" \
      && [ "$(od -An -t x1 -j 4 -N 1 "${L#*-> }")" = ' 01' ]; then
```

Code after:
  if [ "_${NVM_OS}" = "_sunos" ]; then
    if HOST_ARCH=$(pkg_info -Q MACHINE_ARCH pkg_install); then
      HOST_ARCH=$(nvm_echo "${HOST_ARCH}" | command tail -1)
    else
      HOST_ARCH=$(isainfo -n)
    fi
  elif [ "_${NVM_OS}" = "_aix" ]; then
    HOST_ARCH=ppc64
  else
    HOST_ARCH="$(command uname -m)"
  fi

  local NVM_ARCH
  case "${HOST_ARCH}" in
    x86_64 | amd64) NVM_ARCH="x64" ;;
    i*86) NVM_ARCH="x86" ;;
    aarch64) NVM_ARCH="arm64" ;;
    *) NVM_ARCH="${HOST_ARCH}" ;;
  esac

  # If running a 64bit ARM kernel but a 32bit ARM userland,
  # change ARCH to 32bit ARM (armv7l) if /sbin/init is 32bit executable
  local L
  if [ "$(uname)" = "Linux" ] && [ "${NVM_ARCH}" = arm64 ] &&
    L="$(ls -dl /sbin/init 2>/dev/null)" &&
    [ "$(od -An -t x1 -j 4 -N 1 "${L#*-> }")" = ' 01' ]; then
    NVM_ARCH=armv7l
    HOST_ARCH=armv7l
  fi

  nvm_echo "${NVM_ARCH}"
}

nvm_get_minor_version() {
  local VERSION
  VERSION="$1"

  if [ -z "${VERSION}" ]; then
    nvm_err 'a version is required'
    return 1
  fi

  case "${VERSION}" in
    v | .* | *..* | v*[!.0123456789]* | [!v]*[!.0123456789]* | [!v0123456789]* | v[!0123456789]*)
      nvm_err 'invalid version number'
      return 2
    ;;
  esac

  local PREFIXED_VERSION
  PREFIXED_VERSION="$(nvm_format_version "${VERSION}")"
Repository: nvm-sh/nvm
File: nvm.sh (Shell)

Code before:
nvm_cache_dir() {
  nvm_echo "${NVM_DIR}/.cache"
}

nvm() {
  if [ "$#" -lt 1 ]; then
    nvm --help
    return
  fi

  local IFS
  IFS=" $(nvm_echo t | command tr t \\t)
"
  local OPTIONS=''
  local O='e a'
  # set +E only disables errtrace on Bash
  [ -z "${BASH-}" ] || O='e a E'
  for O in $O; do
    if [ "${-#*$O}" != "$-" ]; then
      set "+$O"
      OPTIONS="${OPTIONS}${O}"
    fi
  done
  if [ -n "$OPTIONS" ]; then
    local EXIT_CODE
    nvm "$@"
    EXIT_CODE="$?"
    set "-$OPTIONS"
    return "$EXIT_CODE"
  fi

  local i
  for i in "$@"
  do
    case $i in
      --) break ;;
      '-h'|'help'|'--help')
        NVM_NO_COLORS=""
        for j in "$@"; do
          if [ "${j}" = '--no-colors' ]; then
            NVM_NO_COLORS="${j}"
            break
          fi
        done

        local INITIAL_COLOR_INFO
        local RED_INFO
        local GREEN_INFO
        local BLUE_INFO
        local CYAN_INFO
        local MAGENTA_INFO

Review comment (suggestion):
This indeed isn’t the same; non-exported variables don’t inherit to subshells everywhere.
```suggestion
    IFS=“${IFS}” nvm "$@"
```
that’s why i named it default_ifs - to highlight that it’s different on purpose.


Code after:
nvm_cache_dir() {
  nvm_echo "${NVM_DIR}/.cache"
}

nvm() {
  if [ "$#" -lt 1 ]; then
    nvm --help
    return
  fi

  local DEFAULT_IFS
  DEFAULT_IFS=" $(nvm_echo t | command tr t \\t)
"
  if [ "${-#*e}" != "$-" ]; then
    set +e
    local EXIT_CODE
    IFS="${DEFAULT_IFS}" nvm "$@"
    EXIT_CODE="$?"
    set -e
    return "$EXIT_CODE"
  elif [ "${-#*a}" != "$-" ]; then
    set +a
    local EXIT_CODE
    IFS="${DEFAULT_IFS}" nvm "$@"
    EXIT_CODE="$?"
    set -a
    return "$EXIT_CODE"
  elif [ -n "${BASH-}" ] && [ "${-#*E}" != "$-" ]; then
    # shellcheck disable=SC3041
    set +E
    local EXIT_CODE
    IFS="${DEFAULT_IFS}" nvm "$@"
    EXIT_CODE="$?"
    # shellcheck disable=SC3041
    set -E
    return "$EXIT_CODE"
  elif [ "${IFS}" != "${DEFAULT_IFS}" ]; then
    IFS="${DEFAULT_IFS}" nvm "$@"
    return "$?"
  fi

  local i
  for i in "$@"
  do
    case $i in
      --) break ;;
      '-h'|'help'|'--help')
        NVM_NO_COLORS=""
        for j in "$@"; do
          if [ "${j}" = '--no-colors' ]; then
            NVM_NO_COLORS="${j}"
Repository: nvm-sh/nvm
File: nvm.sh (Shell)

Code before:
    fi

    eval "curl -q --fail ${CURL_COMPRESSED_FLAG:-} ${CURL_HEADER_FLAG:-} $@"
  elif nvm_has "wget"; then
    # Emulate curl with wget
    ARGS=$(nvm_echo "$@" | command sed -e 's/--progress-bar /--progress=bar /' \
                            -e 's/--compressed //' \
                            -e 's/--fail //' \
                            -e 's/-L //' \
                            -e 's/-I /--server-response /' \
                            -e 's/-s /-q /' \
                            -e 's/-sS /-nv /' \
                            -e 's/-o /-O /' \
                            -e 's/-C - /-c /')

    if [ -n "$NVM_AUTH_HEADER" ]; then
      ARGS="$ARGS --header \"$NVM_AUTH_HEADER\""
    fi
    # shellcheck disable=SC2086
    eval wget $ARGS
  fi
}

nvm_sanitize_auth_header() {
    # Remove potentially dangerous characters
    echo "$1" | sed 's/[^a-zA-Z0-9:;_. -]//g'
}

nvm_has_system_node() {
  [ "$(nvm deactivate >/dev/null 2>&1 && command -v node)" != '' ]
}

nvm_has_system_iojs() {
  [ "$(nvm deactivate >/dev/null 2>&1 && command -v iojs)" != '' ]
}

nvm_is_version_installed() {
  if [ -z "${1-}" ]; then
    return 1
  fi
  local NVM_NODE_BINARY
  NVM_NODE_BINARY='node'
  if [ "_$(nvm_get_os)" = '_win' ]; then
    NVM_NODE_BINARY='node.exe'
  fi
  if [ -x "$(nvm_version_path "$1" 2>/dev/null)/bin/${NVM_NODE_BINARY}" ]; then
    return 0
  fi
  return 1
}


Review comment (suggestion):
```suggestion
    nvm_echo "$1" | command sed 's/[^a-zA-Z0-9:;_. -]//g'
```

Code after:
    fi
    eval "curl -q --fail ${CURL_COMPRESSED_FLAG:-} ${CURL_HEADER_FLAG:-} $*"
  elif nvm_has "wget"; then
    # Emulate curl with wget
    ARGS=$(nvm_echo "$@" | command sed -e 's/--progress-bar /--progress=bar /' \
                            -e 's/--compressed //' \
                            -e 's/--fail //' \
                            -e 's/-L //' \
                            -e 's/-I /--server-response /' \
                            -e 's/-s /-q /' \
                            -e 's/-sS /-nv /' \
                            -e 's/-o /-O /' \
                            -e 's/-C - /-c /')

    if [ -n "${NVM_AUTH_HEADER:-}" ]; then
      ARGS="${ARGS} --header \"${NVM_AUTH_HEADER}\""
    fi
    # shellcheck disable=SC2086
    eval wget $ARGS
  fi
}

nvm_sanitize_auth_header() {
    # Remove potentially dangerous characters
    nvm_echo "$1" | command sed 's/[^a-zA-Z0-9:;_. -]//g'
}

nvm_has_system_node() {
  [ "$(nvm deactivate >/dev/null 2>&1 && command -v node)" != '' ]
}

nvm_has_system_iojs() {
  [ "$(nvm deactivate >/dev/null 2>&1 && command -v iojs)" != '' ]
}

nvm_is_version_installed() {
  if [ -z "${1-}" ]; then
    return 1
  fi
  local NVM_NODE_BINARY
  NVM_NODE_BINARY='node'
  if [ "_$(nvm_get_os)" = '_win' ]; then
    NVM_NODE_BINARY='node.exe'
  fi
  if [ -x "$(nvm_version_path "$1" 2>/dev/null)/bin/${NVM_NODE_BINARY}" ]; then
    return 0
  fi
  return 1
}

nvm_print_npm_version() {
Repository: ollama/ollama
File: ollama/cmd/server.py (Python)

Code before:
from aiohttp import web

from ollama import engine


def set_parser(parser):
    parser.add_argument('--host', default='127.0.0.1')
    parser.add_argument('--port', default=6000)
    parser.set_defaults(fn=serve)


def serve(models_home='.', *args, **kwargs):
    app = web.Application()
    app.add_routes([
        web.post('/generate', generate),
    ])

    app.update({
        'llms': {},
        'models_home': models_home,
    })

    web.run_app(app, **kwargs)


async def generate(request):
    body = await request.json()
    model = body.get('model')
    if not model:
        raise web.HTTPBadRequest()

    prompt = body.get('prompt')
    if not prompt:

Review comment (suggestion):
```suggestion
    parser.add_argument('--port', default=7734)
```
I changed this at the same time

Code after:
from aiohttp import web

from ollama import engine


def set_parser(parser):
    parser.add_argument('--host', default='127.0.0.1')
    parser.add_argument('--port', default=7734)
    parser.set_defaults(fn=serve)


def serve(models_home='.', *args, **kwargs):
    app = web.Application()
    app.add_routes([
        web.post('/load', load),
        web.post('/unload', unload),
        web.post('/generate', generate),
    ])

    app.update({
        'llms': {},
        'models_home': models_home,
    })

    web.run_app(app, **kwargs)


async def load(request):
    body = await request.json()
    model = body.get('model')
    if not model:
        raise web.HTTPBadRequest()
Repository: ollama/ollama
File: ollama/cmd/server.py (Python)

Code before:
from aiohttp import web

from ollama import engine


def set_parser(parser):
    parser.add_argument('--host', default='127.0.0.1')
    parser.add_argument('--port', default=7728)
    parser.set_defaults(fn=serve)


def serve(models_home='.', *args, **kwargs):
    app = web.Application()
    app.add_routes([
        web.post('/load', load),
        web.post('/unload', unload),
        web.post('/generate', generate),
    ])

    app.update({
        'llms': {},
        'models_home': models_home,
    })

    web.run_app(app, **kwargs)


async def load(request):
    body = await request.json()
    model = body.get('model')
    if not model:
        raise web.HTTPBadRequest()


Review comment (suggestion):
```suggestion
    parser.add_argument('--port', default=7734)
```
sorry, I might have mis-typed, this one matches the ui

Code after:
from aiohttp import web

from ollama import engine


def set_parser(parser):
    parser.add_argument('--host', default='127.0.0.1')
    parser.add_argument('--port', default=7734)
    parser.set_defaults(fn=serve)


def serve(models_home='.', *args, **kwargs):
    app = web.Application()
    app.add_routes([
        web.post('/load', load),
        web.post('/unload', unload),
        web.post('/generate', generate),
    ])

    app.update({
        'llms': {},
        'models_home': models_home,
    })

    web.run_app(app, **kwargs)


async def load(request):
    body = await request.json()
    model = body.get('model')
    if not model:
        raise web.HTTPBadRequest()
Repository: ollama/ollama
File: cmd/cmd.go (Go)

Code before:

func RunRun(cmd *cobra.Command, args []string) error {
	_, err := os.Stat(args[0])
	switch {
	case errors.Is(err, os.ErrNotExist):
		if err := pull(args[0]); err != nil {
			return err
		}
	case err != nil:
		return err
	}

	return RunGenerate(cmd, args)
}

func pull(model string) error {
	client := api.NewClient()
	var bar *progressbar.ProgressBar
	return client.Pull(
		context.Background(),
		&api.PullRequest{Model: model},
		func(progress api.PullProgress) error {
			if progress.Error.Code == http.StatusBadGateway {
				// couldn't pull the model from the directory, proceed in offline mode
				return nil
			}
			if bar == nil && progress.Percent == 100 {
				// already downloaded
				return nil
			}
			if bar == nil {
				bar = progressbar.DefaultBytes(progress.Total)
			}

			return bar.Set64(progress.Completed)
		},
	)
}

func RunGenerate(_ *cobra.Command, args []string) error {
	if len(args) > 1 {
		return generateOneshot(args[0], args[1:]...)
	}

	if term.IsTerminal(int(os.Stdin.Fd())) {
		return generateInteractive(args[0])
	}

	return generateBatch(args[0])
}


Review comment (suggestion):
IMO this should return nil on any error and fall back to call generate. That way, a user can create a file in `~/.ollama/models` and run it by name without specifying a full path

Code after:
func RunRun(cmd *cobra.Command, args []string) error {
	_, err := os.Stat(args[0])
	switch {
	case errors.Is(err, os.ErrNotExist):
		if err := pull(args[0]); err != nil {
			return err
		}
	case err != nil:
		return err
	}

	return RunGenerate(cmd, args)
}

func pull(model string) error {
	client := api.NewClient()
	var bar *progressbar.ProgressBar
	return client.Pull(
		context.Background(),
		&api.PullRequest{Model: model},
		func(progress api.PullProgress) error {
			if bar == nil && progress.Percent == 100 {
				// already downloaded
				return nil
			}
			if bar == nil {
				bar = progressbar.DefaultBytes(progress.Total)
			}

			return bar.Set64(progress.Completed)
		},
	)
}

func RunGenerate(_ *cobra.Command, args []string) error {
	if len(args) > 1 {
		return generateOneshot(args[0], args[1:]...)
	}

	if term.IsTerminal(int(os.Stdin.Fd())) {
		return generateInteractive(args[0])
	}

	return generateBatch(args[0])
}

func generate(model, prompt string) error {
	if len(strings.TrimSpace(prompt)) > 0 {
		client := api.NewClient()

		spinner := progressbar.NewOptions(-1,
Repository: ollama/ollama
File: server/routes.go (Go)

Code before:
		c.Status(http.StatusOK)
	})

	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
	r.POST("/api/embedding", EmbeddingHandler)
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
	r.POST("/api/copy", CopyModelHandler)
	r.GET("/api/tags", ListModelsHandler)
	r.DELETE("/api/delete", DeleteModelHandler)

	log.Printf("Listening on %s", ln.Addr())
	s := &http.Server{
		Handler: r,
	}

	return s.Serve(ln)
}

func streamResponse(c *gin.Context, ch chan any) {
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

		bts, err := json.Marshal(val)
		if err != nil {
			log.Printf("streamResponse: json.Marshal failed with %s", err)
			return false
		}

		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
			log.Printf("streamResponse: w.Write failed with %s", err)
			return false
		}

		return true
	})
}


Review comment (suggestion):
Consider `embeddings` as it responds with a list of embeddings

```suggestion
	r.POST("/api/embeddings", EmbeddingHandler)
```

Code after:
		c.String(http.StatusOK, "Ollama is running")
	})
	r.HEAD("/", func(c *gin.Context) {
		c.Status(http.StatusOK)
	})

	r.POST("/api/pull", PullModelHandler)
	r.POST("/api/generate", GenerateHandler)
	r.POST("/api/embeddings", EmbeddingHandler)
	r.POST("/api/create", CreateModelHandler)
	r.POST("/api/push", PushModelHandler)
	r.POST("/api/copy", CopyModelHandler)
	r.GET("/api/tags", ListModelsHandler)
	r.DELETE("/api/delete", DeleteModelHandler)

	log.Printf("Listening on %s", ln.Addr())
	s := &http.Server{
		Handler: r,
	}

	return s.Serve(ln)
}

func streamResponse(c *gin.Context, ch chan any) {
	c.Header("Content-Type", "application/x-ndjson")
	c.Stream(func(w io.Writer) bool {
		val, ok := <-ch
		if !ok {
			return false
		}

		bts, err := json.Marshal(val)
		if err != nil {
			log.Printf("streamResponse: json.Marshal failed with %s", err)
			return false
		}

		bts = append(bts, '\n')
		if _, err := w.Write(bts); err != nil {
			log.Printf("streamResponse: w.Write failed with %s", err)
			return false
		}

		return true
	})
}
Repository: ollama/ollama
File: cmd/cmd.go (Go)

Code before:
		readline.PcItem("help"),
		readline.PcItem("list"),
		readline.PcItem("set",
			readline.PcItem("history"),
			readline.PcItem("nohistory"),
			readline.PcItem("mode",
				readline.PcItem("vim"),
				readline.PcItem("emacs"),
				readline.PcItem("default"),
			),
		),
		readline.PcItem("exit"),
		readline.PcItem("bye"),
	)

	usage := func() {
		fmt.Fprintln(os.Stderr, "usage:")
		fmt.Fprintln(os.Stderr, completer.Tree("  "))
	}

	config := readline.Config{
		Prompt:       ">>> ",
		HistoryFile:  filepath.Join(home, ".ollama", "history"),
		AutoComplete: completer,
	}

	scanner, err := readline.NewEx(&config)
	if err != nil {
		return err
	}
	defer scanner.Close()

	// disable history by default
	scanner.HistoryDisable()

	for {
		line, err := scanner.Readline()
		switch {
		case errors.Is(err, io.EOF):
			return nil
		case errors.Is(err, readline.ErrInterrupt):
			continue
		case err != nil:
			return err
		}

		line = strings.TrimSpace(line)

		switch {
		case strings.HasPrefix(line, "list"):
			args := strings.Fields(line)

Review comment (suggestion):
@mchiang0610 had a great idea which was maybe we add a `/clear` command or something like that which would wipe out the current history. I think we should have history turned on by default though because it's so useful to run a command again and switch models.

Code after:
	completer := readline.NewPrefixCompleter(
		readline.PcItem("/help"),
		readline.PcItem("/list"),
		readline.PcItem("/set",
			readline.PcItem("history"),
			readline.PcItem("nohistory"),
			readline.PcItem("verbose"),
			readline.PcItem("quiet"),
			readline.PcItem("mode",
				readline.PcItem("vim"),
				readline.PcItem("emacs"),
				readline.PcItem("default"),
			),
		),
		readline.PcItem("/exit"),
		readline.PcItem("/bye"),
	)

	usage := func() {
		fmt.Fprintln(os.Stderr, "commands:")
		fmt.Fprintln(os.Stderr, completer.Tree("  "))
	}

	config := readline.Config{
		Prompt:       ">>> ",
		HistoryFile:  filepath.Join(home, ".ollama", "history"),
		AutoComplete: completer,
	}

	scanner, err := readline.NewEx(&config)
	if err != nil {
		return err
	}
	defer scanner.Close()

	for {
		line, err := scanner.Readline()
		switch {
		case errors.Is(err, io.EOF):
			return nil
		case errors.Is(err, readline.ErrInterrupt):
			continue
		case err != nil:
			return err
		}

		line = strings.TrimSpace(line)

		switch {
		case strings.HasPrefix(line, "/list"):
			args := strings.Fields(line)
Repository: ollama/ollama
File: cmd/cmd.go (Go)

Code before:
	client := api.NewClient()

	request := api.PushRequest{Name: args[0]}
	fn := func(resp api.ProgressResponse) error {
		fmt.Println(resp.Status)
		return nil
	}

	if err := client.Push(context.Background(), &request, fn); err != nil {
		return err
	}
	return nil
}

func list(cmd *cobra.Command, args []string) error {
	client := api.NewClient()

	models, err := client.List(context.Background())
	if err != nil {
		return err
	}

	var data [][]string

	for _, m := range models.Models {
		name, _, _ := strings.Cut(m.Name, ":")
		if len(args) == 0 || name == args[0] {
			data = append(data, []string{m.Name, humanize.Bytes(uint64(m.Size)), format.HumanTime(m.ModifiedAt, "Never")})
		}
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"NAME", "SIZE", "MODIFIED"})
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetHeaderLine(false)
	table.SetBorder(false)
	table.SetNoWhiteSpace(true)
	table.SetTablePadding("\t")
	table.AppendBulk(data)
	table.Render()

	return nil
}

func RunPull(cmd *cobra.Command, args []string) error {
	return pull(args[0])
}

func pull(model string) error {
	client := api.NewClient()

Review comment (suggestion):
this feels weird to me. If there are larger image named (e.g. `localhost:4000/my_org/my_repo:latest` you would have to type out all of `localhost:4000/my_org/my_repo` to get a list of tags`.

I think it'd be simpler to just do `strings.HasPrefix()`

Code after:
	client := api.NewClient()

	request := api.PushRequest{Name: args[0]}
	fn := func(resp api.ProgressResponse) error {
		fmt.Println(resp.Status)
		return nil
	}

	if err := client.Push(context.Background(), &request, fn); err != nil {
		return err
	}
	return nil
}

func list(cmd *cobra.Command, args []string) error {
	client := api.NewClient()

	models, err := client.List(context.Background())
	if err != nil {
		return err
	}

	var data [][]string

	for _, m := range models.Models {
		if len(args) == 0 || strings.HasPrefix(m.Name, args[0]) {
			data = append(data, []string{m.Name, humanize.Bytes(uint64(m.Size)), format.HumanTime(m.ModifiedAt, "Never")})
		}
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"NAME", "SIZE", "MODIFIED"})
	table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
	table.SetAlignment(tablewriter.ALIGN_LEFT)
	table.SetHeaderLine(false)
	table.SetBorder(false)
	table.SetNoWhiteSpace(true)
	table.SetTablePadding("\t")
	table.AppendBulk(data)
	table.Render()

	return nil
}

func RunPull(cmd *cobra.Command, args []string) error {
	return pull(args[0])
}

func pull(model string) error {
	client := api.NewClient()