openCivilisation
openCivilisation

Reputation: 946

Is it possible to create a new git repository from a template only using the command line?

Creating a new repo using another as a template is a great function, but I can only see how to use this ability on github.com. Can it be done entirely from command line? Perhaps without a remote?

I would like to use templates for a user to intialise a repo to store their secrets in, and it may not even require a remote, but its very important that it isn't connected to the original template repo for privacy. The .gitignore file and the folder tree provided are the most important functions that I'm hoping to provide the user with this ability.

Upvotes: 21

Views: 17261

Answers (4)

jthill
jthill

Reputation: 60393

Create your template repo. Put it (the contents of the .git dir if it's not bare) somewhere they can reach with a filesystem path. Clean out anything you don't want. Then they can git init --template=/path/to/that/template.

Since the template directory isn't named .git you can even make a repository to track it and publish that, then people can clone your template and use its work tree as a template.

Upvotes: 1

Vadorequest
Vadorequest

Reputation: 18009

The existing answers are great for simple use cases, but I wanted to do something a bit more specific to my use-case:

  • Reuse an existing repo (GitHub template)
  • Keep the history of the source
  • Clone locally + create repo on GitHub
  • Configure the new repo automatically (private, default description, enable squash, ...)
  • Configure the remote and fetch branches from all remotes (to keep the new project up-to-date with the template easily)
  • Through a single command that I can quickly adapt to deploy new projects

Here is what I came up with:

cd ~/dev \
&& gh repo create NEW_REPO \
--template OWNER/SOURCE_REPO \
--private \
--clone \
&& cd NEW_REPO \
&& gh repo edit OWNER/NEW_REPO \
--delete-branch-on-merge \
--description "Default description for NEW_REPO." \
--enable-squash-merge \
&& gh repo sync OWNER/NEW_REPO \
--source OWNER/SOURCE_REPO \
--force \
&& git remote add template [email protected]:OWNER/SOURCE_REPO.git \
&& git fetch --all

Note that I first change directory to ~/dev, you might want to change that.

Upvotes: 2

VonC
VonC

Reputation: 1326776

June 2020: Since a template repository such as this one is a GitHub repository, you can:

That way, everything is done form the command line.


Update Sept. 2020: the other approach through the GitHub CLI tool gh, and mentions in Ben Gubler's answer, stems from PR 1590: "Create repositories from a template repo" from Mislav Marohnić and Colin Shum.
(merged in commit 99372f0)

gh repo create <new-repo-name> --template="<link-to-template-repo>"
# OR
gh repo create <new-repo-name> --template="<owner/template-repo>"

Upvotes: 23

Ben Gubler
Ben Gubler

Reputation: 1441

Try gh repo create myrepo --template someuser/sometemplate

Upvotes: 14

Related Questions