starter

package module
v0.0.0-...-4dce253 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2020 License: MIT Imports: 19 Imported by: 0

README

Starter

English

  • 文档:
  • 协议: MIT

功能特性

TODO:

  • 跨平台: 官方支持Windows, Mac 和 Linux;
  • 使用Starter无需懂得编写代码
  • 项目模板可以用于任何编程语言或者标记格式: Python, JavaScript, Ruby, CoffeeScript, RST, Markdown, CSS, HTML 等等. 你也可以在同一项目下使用多种语言
  • 简单命令行使用:
  • 在终端命令行中使用:
  • 或在Golang项目中作为一个package使用:
  • 目录名和文件名同样可以模板。 例如:
  • 支持目录的无限层级嵌套.(唯一的限制就是操作系统的限制)
  • 模板化100%由pongo2完成 ,这包括文件名和目录名.
  • 可以在 starter.json 文件中简单定义模板变量. 例如:
  • 除非添加 --no-input选项, 你将会被交互式提示输入:
    • 提示要输入的对象定义在starter.json.
    • 缺省值为 starter.json中定义的.
    • 输入提示是有序的.
  • 跨平台支持~/.starterrc 文件:
  • Starters (被克隆的Starter项目模板)缺省被放置在~/.starters/ ,如果需要特殊指定,将会保存到指定的starters_dir
  • 如果你已经克隆了一个starter保存到~/.starters/,你可以通过目录名引用它:
  • 你可以直接使用本地starters, 或远程Git仓库。
  • 缺省上下文: 可以为生成项目指定键值对作为缺省值
  • 使用命令行参数注入额外的上下文:
  • 直接访问Starter的API允许注入额外上下文。
  • 前置钩子、后置钩子: 在生成项目前后可以执行的一些额外动作(缺省支持starter预定义的一些命令,如果平台运行也可以是其他一些脚本,如Python、Shell、PowerShell
  • 本地项目的路径可以指定为相对路径或绝对路径
  • 缺省项目将会生成到当前目录,如果需要特别指定其他目录可以使用-o选项。

Acknowledgements

Documentation

Overview

* @Desc: environment and extensions loading. * @Author: TaceyWong * @Date: 2020-09-23 17:02:11 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 17:44:26

* All exceptions used in the Starter code base are defined here. * @Author: TaceyWong * @Date: 2020-09-23 17:00:44 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 17:30:34

* extensions. * @Author: TaceyWong * @Date: 2020-09-23 17:02:00 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 17:45:00

* Functions for generating a project from a project template. * @Author: TaceyWong * @Date: 2020-09-23 17:00:57 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 17:48:32

* Functions for discovering and executing various Starter hooks. * @Author: TaceyWong * @Date: 2020-09-23 16:58:43 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 18:07:34

* Module for setting up logging. * @Author: TaceyWong * @Date: 2020-09-23 17:01:33 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 19:25:29

* Functions for prompting the user for project info. * @Author: TaceyWong * @Date: 2020-09-23 16:59:15 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 19:24:56

* Replay Starter action * @Author: TaceyWong * @Date: 2020-09-23 16:59:26 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-27 14:50:38

* Starter repository functions. * @Author: TaceyWong * @Date: 2020-09-23 16:59:40 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 19:36:17

* @Author: TaceyWong * @Date: 2020-09-23 16:59:52 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 17:14:03

* Utility functions for handling and fetching repo archives in zip format * @Author: TaceyWong * @Date: 2020-09-23 17:00:26 * @Last Modified by: TaceyWong * @Last Modified time: 2020-09-23 18:12:04

Index

Constants

View Source
const UserConfigPath string = ""

UserConfigPath location of user's config

Variables

View Source
var (
	// CustomSub stores custom substitution map
	CustomSub map[string]string
	// CustomRuneSub stores custom rune substitution map
	CustomRuneSub map[rune]string

	// MaxLength stores maximum slug length.
	// It's smart so it will cat slug after full word.
	// By default slugs aren't shortened.
	// If MaxLength is smaller than length of the first word, then returned
	// slug will contain only substring from the first word truncated
	// after MaxLength.
	MaxLength int

	// Lowercase defines if the resulting slug is transformed to lowercase.
	// Default is true.
	Lowercase = true
)
View Source
var BuiltinAbbreviations = map[string]string{
	"gh": "https://github.com/{0}.git",
	"gl": "https://gitlab.com/{0}.git",
	"bb": "https://bitbucket.org/{0}",
}

BuiltinAbbreviations built-in cvs format

View Source
var DefaultConfig = map[string]interface{}{
	"starter_dir":     "~/.starter/",
	"replay_dir":      "~/.starter_replay/",
	"default_context": map[string][]string{},
	"abbreviations":   BuiltinAbbreviations,
}

DefaultConfig Starter default config

View Source
var Hooks = []string{"pre_gen_project", "post_gen_project"}
View Source
var Regex = regexp.MustCompile(`((((git|hg)\+)?(git|ssh|file|https?):(//)?)|(\w+@[\w\.]+))`)

Regex something like git:// ssh:// file:// etc.

or
something like user@...

Functions

func Clone

func Clone(repoURL string, checkout string, cloneToDir string, noInput bool) string

Clone Clone a repo to the current directory.

:param repo_url: Repo URL of unknown type. :param checkout: The branch, tag or commit ID to checkout after clone. :param clone_to_dir: The directory to clone to.

Defaults to the current directory.

:param no_input: Suppress all user prompts when calling via API.

func DetermineRepoDir

func DetermineRepoDir(template, abbreviations, cloneToDir string, checkout,
	noInput bool, password, directory string)

DetermineRepoDir Locate the repository directory from a template reference.

Applies repository abbreviations to the template reference. If the template refers to a repository URL, clone it. If the template is a path to a local repository, use it.

:param template: A directory containing a project template directory,

or a URL to a git repository.

:param abbreviations: A dictionary of repository abbreviation definitions. :param clone_to_dir: The directory to clone the repository into. :param checkout: The branch, tag or commit ID to checkout after clone. :param no_input: Prompt the user at command line for manual configuration? :param password: The password to use when extracting the repository. :param directory: Directory within repo where starter.json lives. :return: A tuple containing the starter template directory, and

a boolean descriving whether that directory should be cleaned up
after the template has been instantiated.

:raises: `RepositoryNotFound` if a repository directory could not be found.

func Dump

func Dump(replayDir, templateName, context string)

Dump Write json data to file.

func Example

func Example()

Example placeholder of pongo2

func ExpandAbbreviations

func ExpandAbbreviations(template, abbreviations string)

ExpandAbbreviations Expand abbreviations in a template name.

func FindHook

func FindHook(hookName, hookDir string) []string

FindHook Return a dict of all hook scripts provided.

Must be called with the project template as the current working directory. Dict's key will be the hook/script's name, without extension, while values will be the absolute path to the script. Missing scripts will not be included in the returned dict.

:param hookName: The hook to find :param hooksDir: The hook directory in the template :return: The absolute path to the hook script or null-str-list

func FindTemplate

func FindTemplate(repoDir string) string

FindTemplate Determine which child directory of `repo_dir` is the project template.

:param repoDir: Local directory of newly cloned repo. :returns projectTemplate: Relative path to project template.

func GetConfig

func GetConfig(configPath string) map[string]interface{}

GetConfig Retrieve the config from the specified path, returning a config dict.

func GetFileName

func GetFileName(replayDir, templateName string)

GetFileName Get the name of file.

func GetUserConfig

func GetUserConfig(configFile string, deaultConfig bool) map[string]interface{}

GetUserConfig Return the user config as a dict.

If ``default_config`` is True, ignore ``config_file`` and return default
values for the config parameters.

If a path to a ``config_file`` is given, that is different from the default
location, load the user config from that.

Otherwise look up the config file path in the ``COOKIECUTTER_CONFIG`
environment variable. If set, load the config from this path. This will
raise an error if the specified path is not valid.

If the environment variable is not set, try the default config file path
before falling back to the default config values.

func IdentifyRepo

func IdentifyRepo(repoURL string) (string, string, error)

IdentifyRepo Determine if `repo_url` should be treated as a URL to a git or hg repo.

Repos can be identified by prepending "hg+" or "git+" to the repo URL.

:param repo_url: Repo URL of unknown type. :returns: ('git', repo_url), ('hg', repo_url), or None.

func IsRepoURL

func IsRepoURL(value string) bool

IsRepoURL Return True if value is a repository URL.

func IsSlug

func IsSlug(text string) bool

IsSlug returns True if provided text does not contain white characters, punctuation, all letters are lower case and only from ASCII range. It could contain `-` and `_` but not at the beginning or end of the text. It should be in range of the MaxLength var if specified. All output from slug.Make(text) should pass this test.

func IsZipFile

func IsZipFile(value string) bool

IsZipFile Return True if value is a zip file.

func Load

func Load(replayDir, templateName string)

Load Read json data from file.

func Make

func Make(s string) (slug string)

Make returns slug generated from provided string. Will use "en" as language substitution.

func MakeExecutable

func MakeExecutable(scriptPath string)

MakeExecutable Make `scriptPath` executable

param scriptPath: The file to change mode

func MakeLang

func MakeLang(s string, lang string) (slug string)

MakeLang returns slug generated from provided string and will use provided language for chars substitution.

func MakeSurePathExist

func MakeSurePathExist(path string) bool

func MergeConfigs

func MergeConfigs(defaultC, overwriteC map[string]interface{}) map[string]interface{}

MergeConfigs Recursively update a dict with the key/value pair of another.

Dict values that are dictionaries themselves will be updated, whilst preserving existing keys.

func ProcessJSON

func ProcessJSON(userValue string) (string, error)

ProcessJSON Load user-supplied value as a JSON dict.

:param str userValue: User-supplied value to load as a JSON dict

func PromptAndDelete

func PromptAndDelete(path string, noInput bool) bool

PromptAndDelete Ask user if it's okay to delete the previously-downloaded file/directory.

If yes, delete it. If no, checks to see if the old version should be reused. If yes, it's reused; otherwise, Cookiecutter exits.

:param path: Previously downloaded zipfile. :param noInput: Suppress prompt to delete repo and just delete it. :return: True if the content was deleted

func PromptChoiceForConfig

func PromptChoiceForConfig(starterDict, env map[string]string, key string, options []string, noInput bool)

PromptChoiceForConfig Prompt user with a set of options to choose from.

Each of the possible choices is rendered beforehand.

func PromptForConfig

func PromptForConfig(context string, noInput bool)

PromptForConfig Prompt user to enter a new config.

func ReadRepoPassword

func ReadRepoPassword(password *string, question string) string

ReadRepoPassword Prompt the user to enter a password.

:param str question: Question to the user

func ReadUserChoice

func ReadUserChoice(varName *string, question string, options []string) string

ReadUserChoice Prompt the user to choose from several options for the given variable.

The first item will be returned if no input happens.

:param str varName: Variable as specified in the context :param list options: Sequence of options that are available to select from :return: Exactly one item of “options“ that has been chosen by the user

func ReadUserDict

func ReadUserDict(varName string, defaultValue string)

ReadUserDict Prompt the user to provide a dictionary of data.

:param str varName: Variable as specified in the context :param defaultValue: Value that will be returned if no input is provided :return: A Go map to use in the context.

func ReadUserVariable

func ReadUserVariable(msg string, varName *string, defaultValue string) string

ReadUserVariable Prompt user for variable and return the entered value or given default.

:param str varName: Variable of the context to query the user :param defaultValue: Value that will be returned if no input happens

func ReadUserYesNo

func ReadUserYesNo(confirm *bool, question string, defaultValue bool) bool

ReadUserYesNo Prompt the user to reply with 'yes' or 'no' (or equivalent values).

Note:

Possible choices are 'true', '1', 'yes', 'y' or 'false', '0', 'no', 'n'

:param str question: Question to the user :param defaultValue: Value that will be returned if no input happens

func RenderVariable

func RenderVariable(env, raw string, starterDict map[string]string)

RenderVariable Render the next variable to be displayed in the user prompt.

Inside the prompting taken from the cookiecutter.json file, this renders the next variable. For example, if a project_name is "Peanut Butter Cookie", the repo_name could be be rendered with:

`{{ starter.project_name.replace(" ", "_") }}`.

This is then presented to the user as the default.

:param Environment env: A Jinja2 Environment object. :param raw: The next value to be prompted for by the user. :param dict quicDict: The current context as it's gradually

being populated with variables.

:return: The rendered value for the default variable.

func RepositoryHasStarterJSON

func RepositoryHasStarterJSON(repoDirectory string) bool

RepositoryHasStarterJSON Determine if `repoDirectory` contains a `starter.json` file.

:param repoDirectory: The candidate repository directory. :return: True if the `repo_directory` is valid, else False.

func RmTree

func RmTree(dirPath string)

func RunHook

func RunHook(hookName, projectDir string, context interface{})

RunHook Try to find and execute a hook from the specified project directory.

:param hookName: The hook to execute. :param projectdir: The directory to execute the script from. :param context: Starter project context.

func RunScript

func RunScript(scriptPath, cwd string)

RunScript Execute a script from a working directory.

:param scriptPath: Absolute path to the script to run. :param cwd: The directory to run the script from.

func RunScriptWithContext

func RunScriptWithContext(scriptPath, cwd string, context interface{})

RunScriptWithContext Execute a script after rendering it with Template Engine.

:param scriptPath: Absolute path to the script to run. :param cwd: The directory to run the script from. :param context: Starter project template context.

func Substitute

func Substitute(s string, sub map[string]string) (buf string)

Substitute returns string with superseded all substrings from provided substitution map. Substitution map will be applied in alphabetic order. Many passes, on one substitution another one could apply.

func SubstituteRune

func SubstituteRune(s string, sub map[rune]string) string

SubstituteRune substitutes string chars with provided rune substitution map. One pass.

func UnZip

func UnZip(cloneToDir string, noInput bool, password string) error

func UnZipFromURL

func UnZipFromURL(zipURI string, isURL bool, cloneToDir string, noInput bool, password string) error

func ValidHook

func ValidHook(hookFile, hookName string) bool

ValidHook Determine if a hook file is valid.

:param hookFile: The hook file to consider for validity :param hookName: The hook to find :return: The hook file validity false or true

func WorkIn

func WorkIn(dirname string)

Types

type ConfigDoesNotExistException

type ConfigDoesNotExistException struct {
	StarterException
}

ConfigDoesNotExistException Exception for missing config file.

Raised when get_config() is passed a path to a config file, but no file is found at that path.

type ContextDecodingException

type ContextDecodingException struct {
	StarterException
}

ContextDecodingException Exception for failed JSON decoding.

Raised when a project's JSON context file can not be decoded.

type FailedHookException

type FailedHookException struct {
	StarterException
}

FailedHookException Exception for hook failures.

Raised when a hook script fails.

type InvalidConfiguration

type InvalidConfiguration struct {
	StarterException
}

InvalidConfiguration Exception for invalid configuration file.

Raised if the global configuration file is not valid YAML or is badly constructed.

type InvalidModeException

type InvalidModeException struct {
	StarterException
}

InvalidModeException Exception for incompatible modes.

Raised when cookiecutter is called with both `no_input==True` and `replay==True` at the same time.

type InvalidZipRepository

type InvalidZipRepository struct {
	StarterException
}

InvalidZipRepository Exception for bad zip repo.

Raised when the specified cookiecutter repository isn't a valid Zip archive.

type MissingProjectDir

type MissingProjectDir struct {
	StarterException
}

MissingProjectDir Exception for missing generated project directory.

Raised during cleanup when remove_repo() can't find a generated project directory inside of a repo.

type NonTemplatedInputDirException

type NonTemplatedInputDirException struct {
	StarterException
}

NonTemplatedInputDirException Exception for when a project's input dir is not templated.

The name of the input directory should always contain a string that is rendered to something else, so that input_dir != output_dir.

type OutputDirExistsException

type OutputDirExistsException struct {
	StarterException
}

OutputDirExistsException Exception for existing output directory.

Raised when the output directory of the project exists already.

type RepositoryCloneFailed

type RepositoryCloneFailed struct {
	StarterException
}

RepositoryCloneFailed Exception for un-cloneable repo.

Raised when a cookiecutter template can't be cloned.

type RepositoryNotFound

type RepositoryNotFound struct {
	StarterException
}

RepositoryNotFound Exception for missing repo.

Raised when the specified cookiecutter repository doesn't exist.

type Starter

type Starter struct {
}

Starter main struct&executor

func NewStarter

func NewStarter(opt *StarterOption) *Starter

NewStarter create a instance of Starter

func (*Starter) Ask

func (s *Starter) Ask() error

Ask ask-flow

func (*Starter) Clone

func (s *Starter) Clone() error

Clone clone|use-local template

func (*Starter) Generate

func (s *Starter) Generate() error

Generate generate the project

func (*Starter) List

func (s *Starter) List() error

List List installed (locally cloned) templates.

func (*Starter) Run

func (s *Starter) Run() error

Run run full flow

func (*Starter) Touch

func (s *Starter) Touch() error

Touch just like linux-touch(re-clone template)

type StarterException

type StarterException struct {
}

StarterException Base exception class.

All Starter-specific exceptions should subclass this class.

func (*StarterException) Error

func (qe *StarterException) Error() string

type StarterOption

type StarterOption struct {
	Template          string
	Checkout          string
	NoInput           bool
	ExtraContext      interface{}
	Replay            string
	OverwriteIfExists bool
	OutputDir         string
	ConfigFile        string
	UseDefaultConfig  bool
	Password          string
	Directory         string
	SkipIfFileExists  bool
	AcceptHooks       bool
}

StarterOption options for create Starter

type UndefinedVariableInTemplate

type UndefinedVariableInTemplate struct {
	StarterException
}

UndefinedVariableInTemplate Exception for out-of-scope variables.

Raised when a template uses a variable which is not defined in the context

type UnknownExtension

type UnknownExtension struct {
	StarterException
}

UnknownExtension Exception for un-importable extention.

Raised when an environment is unable to import a required extension.

type UnknownRepoType

type UnknownRepoType struct {
	StarterException
}

UnknownRepoType Exception for unknown repo types

Raised if a repo's type cannot be determined.

func (*UnknownRepoType) Error

func (ur *UnknownRepoType) Error() string

type UnknownTemplateDirException

type UnknownTemplateDirException struct {
	StarterException
}

type VCSNotInstalled

type VCSNotInstalled struct {
	StarterException
}

VCSNotInstalled Exception when version control is unavailable.

Raised if the version control system (git or hg) is not installed.

Directories

Path Synopsis
* @Description: 填写描述 * @Author: WangXinyong/TaceyWong * @Date: 2020-09-25 10:27:14 * @LastEditors: WangXinyong/TaceyWong * @LastEditTime: 2020-09-25 13:14:46 * @FilePath: /quick/cmd/cli.go
* @Description: 填写描述 * @Author: WangXinyong/TaceyWong * @Date: 2020-09-25 10:27:14 * @LastEditors: WangXinyong/TaceyWong * @LastEditTime: 2020-09-25 13:14:46 * @FilePath: /quick/cmd/cli.go

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL