{"text":"package slack\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n)\n\n\/\/ ItemReaction is the reactions that have happened on an item.\ntype ItemReaction struct {\n\tName string `json:\"name\"`\n\tCount int `json:\"count\"`\n\tUsers []string `json:\"users\"`\n}\n\n\/\/ ReactedItem is an item that was reacted to, and the details of the\n\/\/ reactions.\ntype ReactedItem struct {\n\tType string\n\tMessage *Message\n\tFile *File\n\tComment *Comment\n\tReactions []ItemReaction\n}\n\n\/\/ AddReactionParameters is the inputs to create a new reaction.\ntype AddReactionParameters struct {\n\tName string\n\tItemRef\n}\n\n\/\/ NewAddReactionParameters initialies the inputs to react to an item.\nfunc NewAddReactionParameters(name string, ref ItemRef) AddReactionParameters {\n\treturn AddReactionParameters{Name: name, ItemRef: ref}\n}\n\n\/\/ RemoveReactionParameters is the inputs to remove an existing reaction.\ntype RemoveReactionParameters struct {\n\tName string\n\tItemRef\n}\n\n\/\/ NewAddReactionParameters initialies the inputs to react to an item.\nfunc NewRemoveReactionParameters(name string, ref ItemRef) RemoveReactionParameters {\n\treturn RemoveReactionParameters{Name: name, ItemRef: ref}\n}\n\n\/\/ GetReactionParameters is the inputs to get reactions to an item.\ntype GetReactionParameters struct {\n\tFull bool\n\tItemRef\n}\n\n\/\/ NewGetReactionParameters initializes the inputs to get reactions to an item.\nfunc NewGetReactionParameters(ref ItemRef) GetReactionParameters {\n\treturn GetReactionParameters{ItemRef: ref}\n}\n\ntype getReactionsResponseFull struct {\n\tM struct {\n\t\tType string\n\t\tM struct {\n\t\t\tReactions []ItemReaction\n\t\t} `json:\"message\"`\n\t\tF struct {\n\t\t\tReactions []ItemReaction\n\t\t} `json:\"file\"`\n\t\tFC struct {\n\t\t\tComment struct {\n\t\t\t\tReactions []ItemReaction\n\t\t\t}\n\t\t} `json:\"file_comment\"`\n\t} `json:\"message\"`\n\tSlackResponse\n}\n\nfunc (res getReactionsResponseFull) extractReactions() []ItemReaction {\n\tswitch res.M.Type {\n\tcase \"message\":\n\t\treturn res.M.M.Reactions\n\tcase \"file\":\n\t\treturn res.M.F.Reactions\n\tcase \"file_comment\":\n\t\treturn res.M.FC.Comment.Reactions\n\t}\n\treturn []ItemReaction{}\n}\n\nconst (\n\tDEFAULT_REACTIONS_USERID = \"\"\n\tDEFAULT_REACTIONS_COUNT = 100\n\tDEFAULT_REACTIONS_PAGE = 1\n\tDEFAULT_REACTIONS_FULL = false\n)\n\n\/\/ ListReactionsParameters is the inputs to find all reactions by a user.\ntype ListReactionsParameters struct {\n\tUser string\n\tCount int\n\tPage int\n\tFull bool\n}\n\n\/\/ NewListReactionsParameters initializes the inputs to find all reactions\n\/\/ performed by a user.\nfunc NewListReactionsParameters(userID string) ListReactionsParameters {\n\treturn ListReactionsParameters{\n\t\tUser: userID,\n\t\tCount: DEFAULT_REACTIONS_COUNT,\n\t\tPage: DEFAULT_REACTIONS_PAGE,\n\t\tFull: DEFAULT_REACTIONS_FULL,\n\t}\n}\n\ntype listReactionsResponseFull struct {\n\tItems []struct {\n\t\tType string\n\t\tM struct {\n\t\t\t*Message\n\t\t\tReactions []ItemReaction\n\t\t} `json:\"message\"`\n\t\tF struct {\n\t\t\t*File\n\t\t\tReactions []ItemReaction\n\t\t} `json:\"file\"`\n\t\tFC struct {\n\t\t\tC struct {\n\t\t\t\t*Comment\n\t\t\t\tReactions []ItemReaction\n\t\t\t} `json:\"comment\"`\n\t\t} `json:\"file_comment\"`\n\t}\n\tPaging `json:\"paging\"`\n\tSlackResponse\n}\n\nfunc (res listReactionsResponseFull) extractReactedItems() []ReactedItem {\n\titems := make([]ReactedItem, len(res.Items))\n\tfor i, input := range res.Items {\n\t\titem := ReactedItem{\n\t\t\tType: input.Type,\n\t\t}\n\t\tswitch input.Type {\n\t\tcase \"message\":\n\t\t\titem.Message = input.M.Message\n\t\t\titem.Reactions = input.M.Reactions\n\t\tcase \"file\":\n\t\t\titem.File = input.F.File\n\t\t\titem.Reactions = input.F.Reactions\n\t\tcase \"file_comment\":\n\t\t\titem.Comment = input.FC.C.Comment\n\t\t\titem.Reactions = input.FC.C.Reactions\n\t\t}\n\t\titems[i] = item\n\t}\n\treturn items\n}\n\n\/\/ AddReaction adds a reaction emoji to a message, file or file comment.\nfunc (api *Slack) AddReaction(params AddReactionParameters) error {\n\tvalues := url.Values{\n\t\t\"token\": {api.config.token},\n\t}\n\tif params.Name != \"\" {\n\t\tvalues.Set(\"name\", params.Name)\n\t}\n\tif params.ChannelId != \"\" {\n\t\tvalues.Set(\"channel\", string(params.ChannelId))\n\t}\n\tif params.Timestamp != \"\" {\n\t\tvalues.Set(\"timestamp\", string(params.Timestamp))\n\t}\n\tif params.FileId != \"\" {\n\t\tvalues.Set(\"file\", string(params.FileId))\n\t}\n\tif params.FileCommentId != \"\" {\n\t\tvalues.Set(\"file_comment\", string(params.FileCommentId))\n\t}\n\tresponse := &SlackResponse{}\n\tif err := parseResponse(\"reactions.add\", values, response, api.debug); err != nil {\n\t\treturn err\n\t}\n\tif !response.Ok {\n\t\treturn errors.New(response.Error)\n\t}\n\treturn nil\n}\n\n\/\/ RemoveReaction removes a reaction emoji from a message, file or file comment.\nfunc (api *Slack) RemoveReaction(params RemoveReactionParameters) error {\n\tvalues := url.Values{\n\t\t\"token\": {api.config.token},\n\t}\n\tif params.Name != \"\" {\n\t\tvalues.Set(\"name\", params.Name)\n\t}\n\tif params.ChannelId != \"\" {\n\t\tvalues.Set(\"channel\", string(params.ChannelId))\n\t}\n\tif params.Timestamp != \"\" {\n\t\tvalues.Set(\"timestamp\", string(params.Timestamp))\n\t}\n\tif params.FileId != \"\" {\n\t\tvalues.Set(\"file\", string(params.FileId))\n\t}\n\tif params.FileCommentId != \"\" {\n\t\tvalues.Set(\"file_comment\", string(params.FileCommentId))\n\t}\n\tresponse := &SlackResponse{}\n\tif err := parseResponse(\"reactions.remove\", values, response, api.debug); err != nil {\n\t\treturn err\n\t}\n\tif !response.Ok {\n\t\treturn errors.New(response.Error)\n\t}\n\treturn nil\n}\n\n\/\/ GetReactions returns details about the reactions on an item.\nfunc (api *Slack) GetReactions(params GetReactionParameters) ([]ItemReaction, error) {\n\tvalues := url.Values{\n\t\t\"token\": {api.config.token},\n\t}\n\tif params.ChannelId != \"\" {\n\t\tvalues.Set(\"channel\", string(params.ChannelId))\n\t}\n\tif params.Timestamp != \"\" {\n\t\tvalues.Set(\"timestamp\", string(params.Timestamp))\n\t}\n\tif params.FileId != \"\" {\n\t\tvalues.Set(\"file\", string(params.FileId))\n\t}\n\tif params.FileCommentId != \"\" {\n\t\tvalues.Set(\"file_comment\", string(params.FileCommentId))\n\t}\n\tif params.Full != DEFAULT_REACTIONS_FULL {\n\t\tvalues.Set(\"full\", fmt.Sprintf(\"%t\", params.Full))\n\t}\n\tresponse := &getReactionsResponseFull{}\n\tif err := parseResponse(\"reactions.get\", values, response, api.debug); err != nil {\n\t\treturn nil, err\n\t}\n\tif !response.Ok {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\treturn response.extractReactions(), nil\n}\n\n\/\/ ListReactions returns information about the items a user reacted to.\nfunc (api *Slack) ListReactions(params ListReactionsParameters) ([]ReactedItem, Paging, error) {\n\tvalues := url.Values{\n\t\t\"token\": {api.config.token},\n\t}\n\tif params.User != DEFAULT_REACTIONS_USERID {\n\t\tvalues.Add(\"user\", params.User)\n\t}\n\tif params.Count != DEFAULT_REACTIONS_COUNT {\n\t\tvalues.Add(\"count\", fmt.Sprintf(\"%d\", params.Count))\n\t}\n\tif params.Page != DEFAULT_REACTIONS_PAGE {\n\t\tvalues.Add(\"page\", fmt.Sprintf(\"%d\", params.Page))\n\t}\n\tif params.Full != DEFAULT_REACTIONS_FULL {\n\t\tvalues.Add(\"full\", fmt.Sprintf(\"%t\", params.Full))\n\t}\n\tresponse := &listReactionsResponseFull{}\n\terr := parseResponse(\"reactions.list\", values, response, api.debug)\n\tif err != nil {\n\t\treturn nil, Paging{}, err\n\t}\n\tif !response.Ok {\n\t\treturn nil, Paging{}, errors.New(response.Error)\n\t}\n\treturn response.extractReactedItems(), response.Paging, nil\n}\nreturn Paging as pointer for consistencypackage slack\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n)\n\n\/\/ ItemReaction is the reactions that have happened on an item.\ntype ItemReaction struct {\n\tName string `json:\"name\"`\n\tCount int `json:\"count\"`\n\tUsers []string `json:\"users\"`\n}\n\n\/\/ ReactedItem is an item that was reacted to, and the details of the\n\/\/ reactions.\ntype ReactedItem struct {\n\tType string\n\tMessage *Message\n\tFile *File\n\tComment *Comment\n\tReactions []ItemReaction\n}\n\n\/\/ AddReactionParameters is the inputs to create a new reaction.\ntype AddReactionParameters struct {\n\tName string\n\tItemRef\n}\n\n\/\/ NewAddReactionParameters initialies the inputs to react to an item.\nfunc NewAddReactionParameters(name string, ref ItemRef) AddReactionParameters {\n\treturn AddReactionParameters{Name: name, ItemRef: ref}\n}\n\n\/\/ RemoveReactionParameters is the inputs to remove an existing reaction.\ntype RemoveReactionParameters struct {\n\tName string\n\tItemRef\n}\n\n\/\/ NewAddReactionParameters initialies the inputs to react to an item.\nfunc NewRemoveReactionParameters(name string, ref ItemRef) RemoveReactionParameters {\n\treturn RemoveReactionParameters{Name: name, ItemRef: ref}\n}\n\n\/\/ GetReactionParameters is the inputs to get reactions to an item.\ntype GetReactionParameters struct {\n\tFull bool\n\tItemRef\n}\n\n\/\/ NewGetReactionParameters initializes the inputs to get reactions to an item.\nfunc NewGetReactionParameters(ref ItemRef) GetReactionParameters {\n\treturn GetReactionParameters{ItemRef: ref}\n}\n\ntype getReactionsResponseFull struct {\n\tM struct {\n\t\tType string\n\t\tM struct {\n\t\t\tReactions []ItemReaction\n\t\t} `json:\"message\"`\n\t\tF struct {\n\t\t\tReactions []ItemReaction\n\t\t} `json:\"file\"`\n\t\tFC struct {\n\t\t\tComment struct {\n\t\t\t\tReactions []ItemReaction\n\t\t\t}\n\t\t} `json:\"file_comment\"`\n\t} `json:\"message\"`\n\tSlackResponse\n}\n\nfunc (res getReactionsResponseFull) extractReactions() []ItemReaction {\n\tswitch res.M.Type {\n\tcase \"message\":\n\t\treturn res.M.M.Reactions\n\tcase \"file\":\n\t\treturn res.M.F.Reactions\n\tcase \"file_comment\":\n\t\treturn res.M.FC.Comment.Reactions\n\t}\n\treturn []ItemReaction{}\n}\n\nconst (\n\tDEFAULT_REACTIONS_USERID = \"\"\n\tDEFAULT_REACTIONS_COUNT = 100\n\tDEFAULT_REACTIONS_PAGE = 1\n\tDEFAULT_REACTIONS_FULL = false\n)\n\n\/\/ ListReactionsParameters is the inputs to find all reactions by a user.\ntype ListReactionsParameters struct {\n\tUser string\n\tCount int\n\tPage int\n\tFull bool\n}\n\n\/\/ NewListReactionsParameters initializes the inputs to find all reactions\n\/\/ performed by a user.\nfunc NewListReactionsParameters(userID string) ListReactionsParameters {\n\treturn ListReactionsParameters{\n\t\tUser: userID,\n\t\tCount: DEFAULT_REACTIONS_COUNT,\n\t\tPage: DEFAULT_REACTIONS_PAGE,\n\t\tFull: DEFAULT_REACTIONS_FULL,\n\t}\n}\n\ntype listReactionsResponseFull struct {\n\tItems []struct {\n\t\tType string\n\t\tM struct {\n\t\t\t*Message\n\t\t\tReactions []ItemReaction\n\t\t} `json:\"message\"`\n\t\tF struct {\n\t\t\t*File\n\t\t\tReactions []ItemReaction\n\t\t} `json:\"file\"`\n\t\tFC struct {\n\t\t\tC struct {\n\t\t\t\t*Comment\n\t\t\t\tReactions []ItemReaction\n\t\t\t} `json:\"comment\"`\n\t\t} `json:\"file_comment\"`\n\t}\n\tPaging `json:\"paging\"`\n\tSlackResponse\n}\n\nfunc (res listReactionsResponseFull) extractReactedItems() []ReactedItem {\n\titems := make([]ReactedItem, len(res.Items))\n\tfor i, input := range res.Items {\n\t\titem := ReactedItem{\n\t\t\tType: input.Type,\n\t\t}\n\t\tswitch input.Type {\n\t\tcase \"message\":\n\t\t\titem.Message = input.M.Message\n\t\t\titem.Reactions = input.M.Reactions\n\t\tcase \"file\":\n\t\t\titem.File = input.F.File\n\t\t\titem.Reactions = input.F.Reactions\n\t\tcase \"file_comment\":\n\t\t\titem.Comment = input.FC.C.Comment\n\t\t\titem.Reactions = input.FC.C.Reactions\n\t\t}\n\t\titems[i] = item\n\t}\n\treturn items\n}\n\n\/\/ AddReaction adds a reaction emoji to a message, file or file comment.\nfunc (api *Slack) AddReaction(params AddReactionParameters) error {\n\tvalues := url.Values{\n\t\t\"token\": {api.config.token},\n\t}\n\tif params.Name != \"\" {\n\t\tvalues.Set(\"name\", params.Name)\n\t}\n\tif params.ChannelId != \"\" {\n\t\tvalues.Set(\"channel\", string(params.ChannelId))\n\t}\n\tif params.Timestamp != \"\" {\n\t\tvalues.Set(\"timestamp\", string(params.Timestamp))\n\t}\n\tif params.FileId != \"\" {\n\t\tvalues.Set(\"file\", string(params.FileId))\n\t}\n\tif params.FileCommentId != \"\" {\n\t\tvalues.Set(\"file_comment\", string(params.FileCommentId))\n\t}\n\tresponse := &SlackResponse{}\n\tif err := parseResponse(\"reactions.add\", values, response, api.debug); err != nil {\n\t\treturn err\n\t}\n\tif !response.Ok {\n\t\treturn errors.New(response.Error)\n\t}\n\treturn nil\n}\n\n\/\/ RemoveReaction removes a reaction emoji from a message, file or file comment.\nfunc (api *Slack) RemoveReaction(params RemoveReactionParameters) error {\n\tvalues := url.Values{\n\t\t\"token\": {api.config.token},\n\t}\n\tif params.Name != \"\" {\n\t\tvalues.Set(\"name\", params.Name)\n\t}\n\tif params.ChannelId != \"\" {\n\t\tvalues.Set(\"channel\", string(params.ChannelId))\n\t}\n\tif params.Timestamp != \"\" {\n\t\tvalues.Set(\"timestamp\", string(params.Timestamp))\n\t}\n\tif params.FileId != \"\" {\n\t\tvalues.Set(\"file\", string(params.FileId))\n\t}\n\tif params.FileCommentId != \"\" {\n\t\tvalues.Set(\"file_comment\", string(params.FileCommentId))\n\t}\n\tresponse := &SlackResponse{}\n\tif err := parseResponse(\"reactions.remove\", values, response, api.debug); err != nil {\n\t\treturn err\n\t}\n\tif !response.Ok {\n\t\treturn errors.New(response.Error)\n\t}\n\treturn nil\n}\n\n\/\/ GetReactions returns details about the reactions on an item.\nfunc (api *Slack) GetReactions(params GetReactionParameters) ([]ItemReaction, error) {\n\tvalues := url.Values{\n\t\t\"token\": {api.config.token},\n\t}\n\tif params.ChannelId != \"\" {\n\t\tvalues.Set(\"channel\", string(params.ChannelId))\n\t}\n\tif params.Timestamp != \"\" {\n\t\tvalues.Set(\"timestamp\", string(params.Timestamp))\n\t}\n\tif params.FileId != \"\" {\n\t\tvalues.Set(\"file\", string(params.FileId))\n\t}\n\tif params.FileCommentId != \"\" {\n\t\tvalues.Set(\"file_comment\", string(params.FileCommentId))\n\t}\n\tif params.Full != DEFAULT_REACTIONS_FULL {\n\t\tvalues.Set(\"full\", fmt.Sprintf(\"%t\", params.Full))\n\t}\n\tresponse := &getReactionsResponseFull{}\n\tif err := parseResponse(\"reactions.get\", values, response, api.debug); err != nil {\n\t\treturn nil, err\n\t}\n\tif !response.Ok {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\treturn response.extractReactions(), nil\n}\n\n\/\/ ListReactions returns information about the items a user reacted to.\nfunc (api *Slack) ListReactions(params ListReactionsParameters) ([]ReactedItem, *Paging, error) {\n\tvalues := url.Values{\n\t\t\"token\": {api.config.token},\n\t}\n\tif params.User != DEFAULT_REACTIONS_USERID {\n\t\tvalues.Add(\"user\", params.User)\n\t}\n\tif params.Count != DEFAULT_REACTIONS_COUNT {\n\t\tvalues.Add(\"count\", fmt.Sprintf(\"%d\", params.Count))\n\t}\n\tif params.Page != DEFAULT_REACTIONS_PAGE {\n\t\tvalues.Add(\"page\", fmt.Sprintf(\"%d\", params.Page))\n\t}\n\tif params.Full != DEFAULT_REACTIONS_FULL {\n\t\tvalues.Add(\"full\", fmt.Sprintf(\"%t\", params.Full))\n\t}\n\tresponse := &listReactionsResponseFull{}\n\terr := parseResponse(\"reactions.list\", values, response, api.debug)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif !response.Ok {\n\t\treturn nil, nil, errors.New(response.Error)\n\t}\n\treturn response.extractReactedItems(), &response.Paging, nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 Google Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\n\/* TODO\n\n- readlink.\n- expose md5 as xattr.\n\n*\/\n\nimport (\n\t\"crypto\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t_ \"crypto\/md5\"\n\n\t\"github.com\/hanwen\/go-fuse\/fuse\"\n\t\"github.com\/hanwen\/go-fuse\/fuse\/nodefs\"\n\t\"github.com\/hanwen\/p4fuse\/p4\"\n)\n\ntype P4Fs struct {\n\tnodefs.FileSystem\n\n\tbackingDir string\n\troot *p4Root\n\tp4 *p4.Conn\n}\n\n\/\/ Creates a new P4FS\nfunc NewP4Fs(conn *p4.Conn, backingDir string) *P4Fs {\n\tfs := &P4Fs{\n\t\tFileSystem: nodefs.NewDefaultFileSystem(),\n\t\tp4: conn,\n\t}\n\n\tfs.backingDir = backingDir\n\tfs.root = &p4Root{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tfs: fs,\n\t}\n\treturn fs\n}\n\nfunc (fs *P4Fs) String() string {\n\treturn \"P4Fuse\"\n}\n\nfunc (fs *P4Fs) Root() nodefs.Node {\n\treturn fs.root\n}\n\nfunc (fs *P4Fs) OnMount(conn *nodefs.FileSystemConnector) {\n\tfs.root.Inode().AddChild(\"head\", fs.root.Inode().New(false, fs.newP4Link()))\n}\n\nfunc (fs *P4Fs) newFolder(path string, change int) *p4Folder {\n\treturn &p4Folder{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tfs: fs,\n\t\tpath: path,\n\t\tchange: change,\n\t}\n}\n\nfunc (fs *P4Fs) newFile(st *p4.Stat) *p4File {\n\tf := &p4File{Node: nodefs.NewDefaultNode(), fs: fs, stat: *st}\n\treturn f\n}\n\nfunc (fs *P4Fs) newP4Link() *p4Link {\n\treturn &p4Link{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tfs: fs,\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntype p4Link struct {\n\tnodefs.Node\n\tfs *P4Fs\n}\n\nfunc (f *p4Link) Deletable() bool {\n\treturn false\n}\n\nfunc (f *p4Link) GetAttr(out *fuse.Attr, file nodefs.File, c *fuse.Context) fuse.Status {\n\tout.Mode = fuse.S_IFLNK\n\treturn fuse.OK\n}\n\nfunc (f *p4Link) Readlink(c *fuse.Context) ([]byte, fuse.Status) {\n\tr, err := f.fs.p4.Changes([]string{\"-s\", \"submitted\", \"-m1\"})\n\tif err != nil {\n\t\tlog.Printf(\"p4.Changes: %v\", err)\n\t\treturn nil, fuse.EIO\n\t}\n\n\tch := r[0].(*p4.Change)\n\treturn []byte(fmt.Sprintf(\"%d\", ch.Change)), fuse.OK\n}\n\ntype p4Root struct {\n\tnodefs.Node\n\tfs *P4Fs\n\n\tlink *p4Link\n}\n\nfunc (f *p4Root) OpenDir(context *fuse.Context) (stream []fuse.DirEntry, status fuse.Status) {\n\treturn []fuse.DirEntry{{Name: \"head\", Mode: fuse.S_IFLNK}}, fuse.OK\n}\n\nfunc (r *p4Root) Lookup(out *fuse.Attr, name string, context *fuse.Context) (node nodefs.Node, code fuse.Status) {\n\tcl, err := strconv.ParseInt(name, 10, 64)\n\tif err != nil {\n\t\treturn nil, fuse.ENOENT\n\t}\n\n\tnode = r.fs.newFolder(\"\", int(cl))\n\tr.Inode().AddChild(name, r.Inode().New(true, node))\n\tnode.GetAttr(out, nil, context)\n\treturn node, fuse.OK\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype p4Folder struct {\n\tnodefs.Node\n\tchange int\n\tpath string\n\tfs *P4Fs\n\n\t\/\/ nil means they haven't been fetched yet.\n\tmu sync.Mutex\n\tfiles map[string]*p4.Stat\n\tfolders map[string]bool\n}\n\nfunc (f *p4Folder) OpenDir(context *fuse.Context) (stream []fuse.DirEntry, status fuse.Status) {\n\tif !f.fetch() {\n\t\treturn nil, fuse.EIO\n\t}\n\tstream = make([]fuse.DirEntry, 0, len(f.files)+len(f.folders))\n\n\tfor n, _ := range f.files {\n\t\tmode := fuse.S_IFREG | 0644\n\t\tstream = append(stream, fuse.DirEntry{Name: n, Mode: uint32(mode)})\n\t}\n\tfor n, _ := range f.folders {\n\t\tmode := fuse.S_IFDIR | 0755\n\t\tstream = append(stream, fuse.DirEntry{Name: n, Mode: uint32(mode)})\n\t}\n\treturn stream, fuse.OK\n}\n\nfunc (f *p4Folder) GetAttr(out *fuse.Attr, file nodefs.File, c *fuse.Context) fuse.Status {\n\tout.Mode = fuse.S_IFDIR | 0755\n\treturn fuse.OK\n}\n\nfunc (f *p4Folder) Deletable() bool {\n\treturn false\n}\n\nfunc (f *p4Folder) fetch() bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tif f.files != nil {\n\t\treturn true\n\t}\n\n\tvar err error\n\tpath := \"\/\/\" + f.path\n\tif !strings.HasSuffix(path, \"\/\") {\n\t\tpath += \"\/\"\n\t}\n\tpath += fmt.Sprintf(\"*@%d\", f.change)\n\n\tfolders, err := f.fs.p4.Dirs([]string{path})\n\tif err != nil {\n\t\tlog.Printf(\"fetch: %v\", err)\n\t\treturn false\n\t}\n\tfiles, err := f.fs.p4.Fstat([]string{path})\n\tif err != nil {\n\t\tlog.Printf(\"fetch: %v\", err)\n\t\treturn false\n\t}\n\n\tf.files = map[string]*p4.Stat{}\n\tfor _, r := range files {\n\t\tif stat, ok := r.(*p4.Stat); ok && stat.HeadAction != \"delete\" {\n\t\t\t_, base := filepath.Split(stat.DepotFile)\n\t\t\tf.files[base] = stat\n\t\t}\n\t}\n\n\tf.folders = map[string]bool{}\n\tfor _, r := range folders {\n\t\tif dir, ok := r.(*p4.Dir); ok {\n\t\t\t_, base := filepath.Split(dir.Dir)\n\t\t\tf.folders[base] = true\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (f *p4Folder) Lookup(out *fuse.Attr, name string, context *fuse.Context) (node nodefs.Node, code fuse.Status) {\n\tf.fetch()\n\n\tif st := f.files[name]; st != nil {\n\t\tnode = f.fs.newFile(st)\n\t} else if f.folders[name] {\n\t\tnode = f.fs.newFolder(filepath.Join(f.path, name), f.change)\n\t} else {\n\t\treturn nil, fuse.ENOENT\n\t}\n\n\tf.Inode().AddChild(name, f.Inode().New(true, node))\n\n\tnode.GetAttr(out, nil, context)\n\treturn node, fuse.OK\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype p4File struct {\n\tnodefs.Node\n\tstat p4.Stat\n\tfs *P4Fs\n\n\tmu sync.Mutex\n\tbacking string\n}\n\nvar modes = map[string]uint32{\n\t\"xtext\": fuse.S_IFREG | 0755,\n\t\"xbinary\": fuse.S_IFREG | 0755,\n\t\"kxtext\": fuse.S_IFREG | 0755,\n\t\"symlink\": fuse.S_IFLNK | 0777,\n}\n\nfunc (f *p4File) Readlink(c *fuse.Context) ([]byte, fuse.Status) {\n\tid := fmt.Sprintf(\"%s#%d\", f.stat.DepotFile, f.stat.HeadRev)\n\tcontent, err := f.fs.p4.Print(id)\n\tif err != nil {\n\t\tlog.Printf(\"p4 print: %v\", err)\n\t\treturn nil, fuse.EIO\n\t}\n\tif len(content) == 0 || content[len(content)-1] != '\\n' {\n\t\tlog.Printf(\"terminating newline for symlink missing: %q\", content)\n\t\treturn nil, fuse.EIO\n\t}\n\treturn content[:len(content)-1], fuse.OK\n}\n\nfunc (f *p4File) GetAttr(out *fuse.Attr, file nodefs.File, c *fuse.Context) fuse.Status {\n\tif m, ok := modes[f.stat.HeadType]; ok {\n\t\tout.Mode = m\n\t} else {\n\t\tout.Mode = fuse.S_IFREG | 0644\n\t}\n\n\tout.Mtime = uint64(f.stat.HeadTime)\n\tout.Size = uint64(f.stat.FileSize)\n\treturn fuse.OK\n}\n\nfunc (f *p4File) fetch() bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tif f.backing != \"\" {\n\t\treturn true\n\t}\n\tid := fmt.Sprintf(\"%s#%d\", f.stat.DepotFile, f.stat.HeadRev)\n\th := crypto.MD5.New()\n\th.Write([]byte(id))\n\tsum := fmt.Sprintf(\"%x\", h.Sum(nil))\n\tdir := filepath.Join(f.fs.backingDir, sum[:2])\n\t_, err := os.Lstat(dir)\n\tif os.IsNotExist(err) {\n\t\tos.Mkdir(dir, 0700)\n\t}\n\n\tdest := fmt.Sprintf(\"%s\/%x\", dir, sum[2:])\n\tif _, err := os.Lstat(dest); err == nil {\n\t\tf.backing = dest\n\t\treturn true\n\t}\n\tcontent, err := f.fs.p4.Print(id)\n\tif err != nil {\n\t\tlog.Printf(\"p4 print error: %v\", err)\n\t\treturn false\n\t}\n\n\ttmp, err := ioutil.TempFile(f.fs.backingDir, \"\")\n\tif err != nil {\n\t\tlog.Printf(\"TempFile: %v\", err)\n\t\treturn false\n\t}\n\n\ttmp.Write(content)\n\ttmp.Close()\n\n\tos.Rename(tmp.Name(), dest)\n\tf.backing = dest\n\treturn true\n}\n\nfunc (f *p4File) Deletable() bool {\n\treturn false\n}\n\nfunc (n *p4File) Open(flags uint32, context *fuse.Context) (file nodefs.File, code fuse.Status) {\n\tif flags&fuse.O_ANYWRITE != 0 {\n\t\treturn nil, fuse.EROFS\n\t}\n\n\tn.fetch()\n\tf, err := os.OpenFile(n.backing, int(flags), 0644)\n\tif err != nil {\n\t\treturn nil, fuse.ToStatus(err)\n\t}\n\treturn nodefs.NewLoopbackFile(f), fuse.OK\n}\nUpdate for Inode.NewChild API change.\/\/ Copyright 2012 Google Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\n\/* TODO\n\n- readlink.\n- expose md5 as xattr.\n\n*\/\n\nimport (\n\t\"crypto\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t_ \"crypto\/md5\"\n\n\t\"github.com\/hanwen\/go-fuse\/fuse\"\n\t\"github.com\/hanwen\/go-fuse\/fuse\/nodefs\"\n\t\"github.com\/hanwen\/p4fuse\/p4\"\n)\n\ntype P4Fs struct {\n\tnodefs.FileSystem\n\n\tbackingDir string\n\troot *p4Root\n\tp4 *p4.Conn\n}\n\n\/\/ Creates a new P4FS\nfunc NewP4Fs(conn *p4.Conn, backingDir string) *P4Fs {\n\tfs := &P4Fs{\n\t\tFileSystem: nodefs.NewDefaultFileSystem(),\n\t\tp4: conn,\n\t}\n\n\tfs.backingDir = backingDir\n\tfs.root = &p4Root{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tfs: fs,\n\t}\n\treturn fs\n}\n\nfunc (fs *P4Fs) String() string {\n\treturn \"P4Fuse\"\n}\n\nfunc (fs *P4Fs) Root() nodefs.Node {\n\treturn fs.root\n}\n\nfunc (fs *P4Fs) OnMount(conn *nodefs.FileSystemConnector) {\n\tfs.root.Inode().NewChild(\"head\", false, fs.newP4Link())\n}\n\nfunc (fs *P4Fs) newFolder(path string, change int) *p4Folder {\n\treturn &p4Folder{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tfs: fs,\n\t\tpath: path,\n\t\tchange: change,\n\t}\n}\n\nfunc (fs *P4Fs) newFile(st *p4.Stat) *p4File {\n\tf := &p4File{Node: nodefs.NewDefaultNode(), fs: fs, stat: *st}\n\treturn f\n}\n\nfunc (fs *P4Fs) newP4Link() *p4Link {\n\treturn &p4Link{\n\t\tNode: nodefs.NewDefaultNode(),\n\t\tfs: fs,\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntype p4Link struct {\n\tnodefs.Node\n\tfs *P4Fs\n}\n\nfunc (f *p4Link) Deletable() bool {\n\treturn false\n}\n\nfunc (f *p4Link) GetAttr(out *fuse.Attr, file nodefs.File, c *fuse.Context) fuse.Status {\n\tout.Mode = fuse.S_IFLNK\n\treturn fuse.OK\n}\n\nfunc (f *p4Link) Readlink(c *fuse.Context) ([]byte, fuse.Status) {\n\tr, err := f.fs.p4.Changes([]string{\"-s\", \"submitted\", \"-m1\"})\n\tif err != nil {\n\t\tlog.Printf(\"p4.Changes: %v\", err)\n\t\treturn nil, fuse.EIO\n\t}\n\n\tch := r[0].(*p4.Change)\n\treturn []byte(fmt.Sprintf(\"%d\", ch.Change)), fuse.OK\n}\n\ntype p4Root struct {\n\tnodefs.Node\n\tfs *P4Fs\n\n\tlink *p4Link\n}\n\nfunc (f *p4Root) OpenDir(context *fuse.Context) (stream []fuse.DirEntry, status fuse.Status) {\n\treturn []fuse.DirEntry{{Name: \"head\", Mode: fuse.S_IFLNK}}, fuse.OK\n}\n\nfunc (r *p4Root) Lookup(out *fuse.Attr, name string, context *fuse.Context) (node nodefs.Node, code fuse.Status) {\n\tcl, err := strconv.ParseInt(name, 10, 64)\n\tif err != nil {\n\t\treturn nil, fuse.ENOENT\n\t}\n\n\tnode = r.fs.newFolder(\"\", int(cl))\n\tr.Inode().NewChild(name, true, node)\n\tnode.GetAttr(out, nil, context)\n\treturn node, fuse.OK\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype p4Folder struct {\n\tnodefs.Node\n\tchange int\n\tpath string\n\tfs *P4Fs\n\n\t\/\/ nil means they haven't been fetched yet.\n\tmu sync.Mutex\n\tfiles map[string]*p4.Stat\n\tfolders map[string]bool\n}\n\nfunc (f *p4Folder) OpenDir(context *fuse.Context) (stream []fuse.DirEntry, status fuse.Status) {\n\tif !f.fetch() {\n\t\treturn nil, fuse.EIO\n\t}\n\tstream = make([]fuse.DirEntry, 0, len(f.files)+len(f.folders))\n\n\tfor n, _ := range f.files {\n\t\tmode := fuse.S_IFREG | 0644\n\t\tstream = append(stream, fuse.DirEntry{Name: n, Mode: uint32(mode)})\n\t}\n\tfor n, _ := range f.folders {\n\t\tmode := fuse.S_IFDIR | 0755\n\t\tstream = append(stream, fuse.DirEntry{Name: n, Mode: uint32(mode)})\n\t}\n\treturn stream, fuse.OK\n}\n\nfunc (f *p4Folder) GetAttr(out *fuse.Attr, file nodefs.File, c *fuse.Context) fuse.Status {\n\tout.Mode = fuse.S_IFDIR | 0755\n\treturn fuse.OK\n}\n\nfunc (f *p4Folder) Deletable() bool {\n\treturn false\n}\n\nfunc (f *p4Folder) fetch() bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tif f.files != nil {\n\t\treturn true\n\t}\n\n\tvar err error\n\tpath := \"\/\/\" + f.path\n\tif !strings.HasSuffix(path, \"\/\") {\n\t\tpath += \"\/\"\n\t}\n\tpath += fmt.Sprintf(\"*@%d\", f.change)\n\n\tfolders, err := f.fs.p4.Dirs([]string{path})\n\tif err != nil {\n\t\tlog.Printf(\"fetch: %v\", err)\n\t\treturn false\n\t}\n\tfiles, err := f.fs.p4.Fstat([]string{path})\n\tif err != nil {\n\t\tlog.Printf(\"fetch: %v\", err)\n\t\treturn false\n\t}\n\n\tf.files = map[string]*p4.Stat{}\n\tfor _, r := range files {\n\t\tif stat, ok := r.(*p4.Stat); ok && stat.HeadAction != \"delete\" {\n\t\t\t_, base := filepath.Split(stat.DepotFile)\n\t\t\tf.files[base] = stat\n\t\t}\n\t}\n\n\tf.folders = map[string]bool{}\n\tfor _, r := range folders {\n\t\tif dir, ok := r.(*p4.Dir); ok {\n\t\t\t_, base := filepath.Split(dir.Dir)\n\t\t\tf.folders[base] = true\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (f *p4Folder) Lookup(out *fuse.Attr, name string, context *fuse.Context) (node nodefs.Node, code fuse.Status) {\n\tf.fetch()\n\n\tif st := f.files[name]; st != nil {\n\t\tnode = f.fs.newFile(st)\n\t} else if f.folders[name] {\n\t\tnode = f.fs.newFolder(filepath.Join(f.path, name), f.change)\n\t} else {\n\t\treturn nil, fuse.ENOENT\n\t}\n\n\tf.Inode().NewChild(name, true, node)\n\n\tnode.GetAttr(out, nil, context)\n\treturn node, fuse.OK\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype p4File struct {\n\tnodefs.Node\n\tstat p4.Stat\n\tfs *P4Fs\n\n\tmu sync.Mutex\n\tbacking string\n}\n\nvar modes = map[string]uint32{\n\t\"xtext\": fuse.S_IFREG | 0755,\n\t\"xbinary\": fuse.S_IFREG | 0755,\n\t\"kxtext\": fuse.S_IFREG | 0755,\n\t\"symlink\": fuse.S_IFLNK | 0777,\n}\n\nfunc (f *p4File) Readlink(c *fuse.Context) ([]byte, fuse.Status) {\n\tid := fmt.Sprintf(\"%s#%d\", f.stat.DepotFile, f.stat.HeadRev)\n\tcontent, err := f.fs.p4.Print(id)\n\tif err != nil {\n\t\tlog.Printf(\"p4 print: %v\", err)\n\t\treturn nil, fuse.EIO\n\t}\n\tif len(content) == 0 || content[len(content)-1] != '\\n' {\n\t\tlog.Printf(\"terminating newline for symlink missing: %q\", content)\n\t\treturn nil, fuse.EIO\n\t}\n\treturn content[:len(content)-1], fuse.OK\n}\n\nfunc (f *p4File) GetAttr(out *fuse.Attr, file nodefs.File, c *fuse.Context) fuse.Status {\n\tif m, ok := modes[f.stat.HeadType]; ok {\n\t\tout.Mode = m\n\t} else {\n\t\tout.Mode = fuse.S_IFREG | 0644\n\t}\n\n\tout.Mtime = uint64(f.stat.HeadTime)\n\tout.Size = uint64(f.stat.FileSize)\n\treturn fuse.OK\n}\n\nfunc (f *p4File) fetch() bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tif f.backing != \"\" {\n\t\treturn true\n\t}\n\tid := fmt.Sprintf(\"%s#%d\", f.stat.DepotFile, f.stat.HeadRev)\n\th := crypto.MD5.New()\n\th.Write([]byte(id))\n\tsum := fmt.Sprintf(\"%x\", h.Sum(nil))\n\tdir := filepath.Join(f.fs.backingDir, sum[:2])\n\t_, err := os.Lstat(dir)\n\tif os.IsNotExist(err) {\n\t\tos.Mkdir(dir, 0700)\n\t}\n\n\tdest := fmt.Sprintf(\"%s\/%x\", dir, sum[2:])\n\tif _, err := os.Lstat(dest); err == nil {\n\t\tf.backing = dest\n\t\treturn true\n\t}\n\tcontent, err := f.fs.p4.Print(id)\n\tif err != nil {\n\t\tlog.Printf(\"p4 print error: %v\", err)\n\t\treturn false\n\t}\n\n\ttmp, err := ioutil.TempFile(f.fs.backingDir, \"\")\n\tif err != nil {\n\t\tlog.Printf(\"TempFile: %v\", err)\n\t\treturn false\n\t}\n\n\ttmp.Write(content)\n\ttmp.Close()\n\n\tos.Rename(tmp.Name(), dest)\n\tf.backing = dest\n\treturn true\n}\n\nfunc (f *p4File) Deletable() bool {\n\treturn false\n}\n\nfunc (n *p4File) Open(flags uint32, context *fuse.Context) (file nodefs.File, code fuse.Status) {\n\tif flags&fuse.O_ANYWRITE != 0 {\n\t\treturn nil, fuse.EROFS\n\t}\n\n\tn.fetch()\n\tf, err := os.OpenFile(n.backing, int(flags), 0644)\n\tif err != nil {\n\t\treturn nil, fuse.ToStatus(err)\n\t}\n\treturn nodefs.NewLoopbackFile(f), fuse.OK\n}\n<|endoftext|>"} {"text":"package service\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/clawio\/codes\"\n)\n\ntype (\n\t\/\/ AuthenticateRequest specifies the data received by the Authenticate endpoint.\n\tAuthenticateRequest struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\n\t\/\/ AuthenticateResponse specifies the data returned from the Authenticate endpoint.\n\tAuthenticateResponse struct {\n\t\tToken string `json:\"token\"`\n\t}\n)\n\n\/\/ Authenticate authenticates an user using an username and a password.\nfunc (s *Service) Authenticate(w http.ResponseWriter, r *http.Request) {\n\tif r.Body == nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tauthReq := &AuthenticateRequest{}\n\tif err := json.NewDecoder(r.Body).Decode(authReq); err != nil {\n\t\te := codes.NewErr(codes.BadInputData, \"\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(e)\n\t\treturn\n\t}\n\ttoken, err := s.AuthenticationController.Authenticate(authReq.Username, authReq.Password)\n\tif err != nil {\n\t\ts.handleAuthenticateError(err, w)\n\t\treturn\n\t}\n\tres := &AuthenticateResponse{Token: token}\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(res)\n}\n\nfunc (s *Service) handleAuthenticateError(err error, w http.ResponseWriter) {\n\te := codes.NewErr(codes.BadInputData, \"user or password do not match\")\n\tw.WriteHeader(http.StatusBadRequest)\n\tjson.NewEncoder(w).Encode(e)\n\treturn\n}\nChange token for access_token in authenticate responsepackage service\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/clawio\/codes\"\n)\n\ntype (\n\t\/\/ AuthenticateRequest specifies the data received by the Authenticate endpoint.\n\tAuthenticateRequest struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\n\t\/\/ AuthenticateResponse specifies the data returned from the Authenticate endpoint.\n\tAuthenticateResponse struct {\n\t\tAccessToken string `json:\"access_token\"`\n\t}\n)\n\n\/\/ Authenticate authenticates an user using an username and a password.\nfunc (s *Service) Authenticate(w http.ResponseWriter, r *http.Request) {\n\tif r.Body == nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tauthReq := &AuthenticateRequest{}\n\tif err := json.NewDecoder(r.Body).Decode(authReq); err != nil {\n\t\te := codes.NewErr(codes.BadInputData, \"\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tjson.NewEncoder(w).Encode(e)\n\t\treturn\n\t}\n\ttoken, err := s.AuthenticationController.Authenticate(authReq.Username, authReq.Password)\n\tif err != nil {\n\t\ts.handleAuthenticateError(err, w)\n\t\treturn\n\t}\n\tres := &AuthenticateResponse{AccessToken: token}\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(res)\n}\n\nfunc (s *Service) handleAuthenticateError(err error, w http.ResponseWriter) {\n\te := codes.NewErr(codes.BadInputData, \"user or password do not match\")\n\tw.WriteHeader(http.StatusBadRequest)\n\tjson.NewEncoder(w).Encode(e)\n\treturn\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"sort\"\n)\n\ntype Charset struct {\n\tFrom, To rune\n}\n\ntype Counter interface {\n\tReadAll(in io.Reader) \/\/ 读取全部\n\tOutput(out io.Writer, mutiline bool) \/\/ 输出\n\tAllCount() int64 \/\/ 全部字符数量\n\tCounted() int \/\/ 计算进的数量\n}\n\n\/\/ 不排序字符统计器\ntype NormalCounter struct {\n\tcount int64\n\n\tm map[rune]int\n\tma []rune\n}\n\nfunc NewNormalCounter() *NormalCounter {\n\treturn &NormalCounter{\n\t\tm: make(map[rune]int),\n\t\tma: make([]rune, 0, 0x9fa5-0x4e00),\n\t}\n}\nfunc (this *NormalCounter) ReadAll(in io.Reader) {\n\tr := bufio.NewReader(in)\n\tfor {\n\t\tru, _, err := r.ReadRune()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif _, ok := this.m[ru]; ru >= 0x4e00 && ru <= 0x9fa5 {\n\t\t\tif !ok {\n\t\t\t\tthis.m[ru] = 0\n\t\t\t\tthis.ma = append(this.ma, ru)\n\t\t\t}\n\t\t\tthis.count++\n\t\t\tthis.m[ru]++\n\t\t}\n\t}\n}\nfunc (this *NormalCounter) Output(out io.Writer, mutiline bool) {\n\tw := bufio.NewWriter(out)\n\tfor _, v := range this.ma {\n\t\tv2 := this.m[v]\n\t\tif mutiline {\n\t\t\tfmt.Fprintf(w, \"%s : %v\\n\", string(v), v2)\n\t\t} else {\n\t\t\tw.WriteRune(v)\n\t\t}\n\t}\n\tw.Flush()\n}\nfunc (this *NormalCounter) AllCount() int64 { return this.count }\nfunc (this *NormalCounter) Counted() int { return len(this.ma) }\n\n\/\/ 排序字符统计器\ntype SortCounter struct {\n\tcount int64\n\t\/\/ charsets []Charset\n\tm map[rune]int\n\trm map[int][]rune\n\tra []int\n}\n\nfunc NewSortCounter() *SortCounter { return &SortCounter{m: make(map[rune]int)} }\nfunc (this *SortCounter) ReadAll(in io.Reader) {\n\tr := bufio.NewReader(in)\n\tfor {\n\t\tru, _, err := r.ReadRune()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif _, ok := this.m[ru]; ru >= 0x4e00 && ru <= 0x9fa5 {\n\t\t\tif !ok {\n\t\t\t\tthis.m[ru] = 0\n\t\t\t}\n\t\t\tthis.count++\n\t\t\tthis.m[ru]++\n\t\t}\n\t}\n}\nfunc (this *SortCounter) Sort() {\n\tthis.rm = make(map[int][]rune)\n\tfor i, v := range this.m {\n\t\tif _, ok := this.rm[v]; !ok {\n\t\t\tthis.rm[v] = make([]rune, 0, 2)\n\t\t}\n\t\tthis.rm[v] = append(this.rm[v], i)\n\t}\n\tthis.ra = make([]int, 0, len(this.rm))\n\tfor i, _ := range this.rm {\n\t\tthis.ra = append(this.ra, i)\n\t}\n\tsort.Ints(this.ra)\n}\nfunc (this *SortCounter) Output(out io.Writer, mutiline bool) {\n\tthis.Sort()\n\tw := bufio.NewWriter(out)\n\tfor i := len(this.ra) - 1; i >= 0; i-- {\n\t\tv := this.ra[i]\n\t\tfor _, v2 := range this.rm[v] {\n\t\t\tif mutiline {\n\t\t\t\tfmt.Fprintf(w, \"%s : %v\\n\", string(v2), v)\n\t\t\t} else {\n\t\t\t\tw.WriteRune(v2)\n\t\t\t}\n\t\t}\n\t}\n\tw.Flush()\n}\nfunc (this *SortCounter) AllCount() int64 { return this.count }\nfunc (this *SortCounter) Counted() int { return len(this.m) }\n\nfunc parseflags() (in string, out string, sort, mutiline, count, random bool) {\n\ti := flag.String(\"i\", \"stdin\", \"the file you want to use\")\n\to := flag.String(\"o\", \"stdout\", \"the file you want to output\")\n\ts := flag.Bool(\"s\", false, \"sort by use times\")\n\tl := flag.Bool(\"l\", false, \"output mutiline text\")\n\tc := flag.Bool(\"c\", false, \"print char count\")\n\th := flag.Bool(\"h\", false, \"show help\")\n\tr := flag.Bool(\"r\", false, \"random output\")\n\tflag.Parse()\n\tif *h {\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\treturn *i, *o, *s, *l, *c, *r\n}\n\nfunc main() {\n\tin, out, isSort, isMutiline, isCount, isRandom := parseflags()\n\tvar fin io.Reader\n\tif in == \"stdin\" {\n\t\tfin = os.Stdin\n\t} else {\n\t\tf, err := os.Open(in)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[ERROR]\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer f.Close()\n\t\tfin = f\n\t}\n\tvar fout io.Writer\n\tif out == \"stdout\" {\n\t\tfout = os.Stdout\n\t} else if out == \"stderr\" {\n\t\tfout = os.Stderr\n\t} else {\n\t\tfw, err := os.Create(out)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[ERROR]\", err)\n\t\t}\n\t\tdefer fw.Close()\n\t\tfout = fw\n\t}\n\tvar co Counter\n\tif isSort {\n\t\tco = NewSortCounter()\n\t} else {\n\t\tco = NewNormalCounter()\n\t}\n\n\t\/\/ stdin 输入下防止坑爹\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tfor _ = range c {\n\t\t\tif isCount {\n\t\t\t\tfmt.Println(\"\\n[All]\", co.AllCount(), \"[Chars]\", co.Counted())\n\t\t\t}\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\tco.ReadAll(fin)\n\tif isRandom {\n\t\tbuf := &bytes.Buffer{}\n\t\tco.Output(buf, false)\n\t\tio.Copy(fout, buf)\n\t} else {\n\t\tco.Output(fout, isMutiline)\n\t}\n\tif isCount {\n\t\tfmt.Println(\"\\n[All]\", co.AllCount(), \"[Chars]\", co.Counted())\n\t}\n}\nupdate charcpackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"sort\"\n)\n\ntype Charset struct {\n\tFrom, To rune\n}\n\ntype Counter interface {\n\tReadAll(in io.Reader) \/\/ 读取全部\n\tOutput(out io.Writer, mutiline bool) \/\/ 输出\n\tAllCount() int64 \/\/ 全部字符数量\n\tCounted() int \/\/ 计算进的数量\n}\n\n\/\/ 不排序字符统计器\ntype NormalCounter struct {\n\tcount int64\n\tisAllChar bool\n\tisSortASCII bool\n\tm map[rune]int\n\tma []rune\n}\n\nfunc NewNormalCounter(allChar, sortASCII bool) *NormalCounter {\n\tmaxcap := 0x9fa5 - 0x4e00\n\tif allChar {\n\t\tmaxcap = 0xffff\n\t}\n\treturn &NormalCounter{\n\t\tm: make(map[rune]int),\n\t\tma: make([]rune, 0, maxcap),\n\t\tisAllChar: allChar,\n\t\tisSortASCII: sortASCII,\n\t}\n}\nfunc (this *NormalCounter) ReadAll(in io.Reader) {\n\tr := bufio.NewReader(in)\n\tfor {\n\t\tru, _, err := r.ReadRune()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif _, ok := this.m[ru]; this.isAllChar || ru >= 0x4e00 && ru <= 0x9fa5 {\n\t\t\tif !ok {\n\t\t\t\tthis.m[ru] = 0\n\t\t\t\tthis.ma = append(this.ma, ru)\n\t\t\t}\n\t\t\tthis.count++\n\t\t\tthis.m[ru]++\n\t\t}\n\t}\n}\nfunc (this *NormalCounter) SortASCII() {\n\tsorter := &runeSorter{this.ma}\n\tsort.Sort(sorter)\n}\n\ntype runeSorter struct{ runes []rune }\n\nfunc (s *runeSorter) Len() int { return len(s.runes) }\nfunc (s *runeSorter) Swap(i, j int) { s.runes[i], s.runes[j] = s.runes[j], s.runes[i] }\nfunc (s *runeSorter) Less(i, j int) bool { return s.runes[i] < s.runes[j] }\n\nfunc (this *NormalCounter) Output(out io.Writer, mutiline bool) {\n\tif this.isSortASCII {\n\t\tthis.SortASCII()\n\t}\n\tw := bufio.NewWriter(out)\n\tfor _, v := range this.ma {\n\t\tv2 := this.m[v]\n\t\tif mutiline {\n\t\t\tfmt.Fprintf(w, \"%s : %v\\n\", string(v), v2)\n\t\t} else {\n\t\t\tw.WriteRune(v)\n\t\t}\n\t}\n\tw.Flush()\n}\nfunc (this *NormalCounter) AllCount() int64 { return this.count }\nfunc (this *NormalCounter) Counted() int { return len(this.ma) }\n\n\/\/ 排序字符统计器\ntype SortCounter struct {\n\tcount int64\n\tisAllChar bool\n\tm map[rune]int\n\trm map[int][]rune\n\tra []int\n}\n\nfunc NewSortCounter(allChar bool) *SortCounter {\n\treturn &SortCounter{m: make(map[rune]int), isAllChar: allChar}\n}\nfunc (this *SortCounter) ReadAll(in io.Reader) {\n\tr := bufio.NewReader(in)\n\tfor {\n\t\tru, _, err := r.ReadRune()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif _, ok := this.m[ru]; this.isAllChar || ru >= 0x4e00 && ru <= 0x9fa5 {\n\t\t\tif !ok {\n\t\t\t\tthis.m[ru] = 0\n\t\t\t}\n\t\t\tthis.count++\n\t\t\tthis.m[ru]++\n\t\t}\n\t}\n}\nfunc (this *SortCounter) Sort() {\n\tthis.rm = make(map[int][]rune)\n\tfor i, v := range this.m {\n\t\tif _, ok := this.rm[v]; !ok {\n\t\t\tthis.rm[v] = make([]rune, 0, 2)\n\t\t}\n\t\tthis.rm[v] = append(this.rm[v], i)\n\t}\n\tthis.ra = make([]int, 0, len(this.rm))\n\tfor i, _ := range this.rm {\n\t\tthis.ra = append(this.ra, i)\n\t}\n\tsort.Ints(this.ra)\n}\nfunc (this *SortCounter) Output(out io.Writer, mutiline bool) {\n\tthis.Sort()\n\tw := bufio.NewWriter(out)\n\tfor i := len(this.ra) - 1; i >= 0; i-- {\n\t\tv := this.ra[i]\n\t\tfor _, v2 := range this.rm[v] {\n\t\t\tif mutiline {\n\t\t\t\tfmt.Fprintf(w, \"%s : %v\\n\", string(v2), v)\n\t\t\t} else {\n\t\t\t\tw.WriteRune(v2)\n\t\t\t}\n\t\t}\n\t}\n\tw.Flush()\n}\nfunc (this *SortCounter) AllCount() int64 { return this.count }\nfunc (this *SortCounter) Counted() int { return len(this.m) }\n\nfunc parseflags() (in string, out string, sort, sortascii, mutiline, allchar, count, random bool) {\n\ti := flag.String(\"i\", \"stdin\", \"the file you want to use\")\n\to := flag.String(\"o\", \"stdout\", \"the file you want to output\")\n\ts := flag.Bool(\"s\", false, \"sort by use times\")\n\tp := flag.Bool(\"p\", false, \"sort by ASCII\")\n\tl := flag.Bool(\"l\", false, \"output mutiline text\")\n\ta := flag.Bool(\"a\", false, \"output all char\")\n\tc := flag.Bool(\"c\", false, \"print char count\")\n\th := flag.Bool(\"h\", false, \"show help\")\n\tr := flag.Bool(\"r\", false, \"random output\")\n\tflag.Parse()\n\tif *h {\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\treturn *i, *o, *s, *p, *l, *a, *c, *r\n}\n\nfunc main() {\n\tin, out, isSort, isSortASCII, isMutiline, isAllChar, isCount, isRandom := parseflags()\n\tvar fin io.Reader\n\tif in == \"stdin\" {\n\t\tfin = os.Stdin\n\t} else {\n\t\tf, err := os.Open(in)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[ERROR]\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer f.Close()\n\t\tfin = f\n\t}\n\tvar fout io.Writer\n\tif out == \"stdout\" {\n\t\tfout = os.Stdout\n\t} else if out == \"stderr\" {\n\t\tfout = os.Stderr\n\t} else {\n\t\tfw, err := os.Create(out)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[ERROR]\", err)\n\t\t}\n\t\tdefer fw.Close()\n\t\tfout = fw\n\t}\n\tvar co Counter\n\tif isSort {\n\t\tco = NewSortCounter(isAllChar)\n\t} else {\n\t\tco = NewNormalCounter(isAllChar, isSortASCII)\n\t}\n\n\t\/\/ stdin 输入下防止坑爹\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tfor _ = range c {\n\t\t\tif isCount {\n\t\t\t\tfmt.Println(\"\\n[All]\", co.AllCount(), \"[Chars]\", co.Counted())\n\t\t\t}\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\tco.ReadAll(fin)\n\tif isRandom {\n\t\tbuf := &bytes.Buffer{}\n\t\tco.Output(buf, false)\n\t\tio.Copy(fout, buf)\n\t} else {\n\t\tco.Output(fout, isMutiline)\n\t}\n\tif isCount {\n\t\tfmt.Println(\"\\n[All]\", co.AllCount(), \"[Chars]\", co.Counted())\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 The Gitea Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage migrations\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"code.gitea.io\/gitea\/modules\/git\"\n\t\"code.gitea.io\/gitea\/modules\/log\"\n\t\"code.gitea.io\/gitea\/modules\/setting\"\n\n\t\"xorm.io\/xorm\"\n)\n\n\/\/ Copy paste from models\/repo.go because we cannot import models package\nfunc repoPath(userName, repoName string) string {\n\treturn filepath.Join(userPath(userName), strings.ToLower(repoName)+\".git\")\n}\n\nfunc userPath(userName string) string {\n\treturn filepath.Join(setting.RepoRootPath, strings.ToLower(userName))\n}\n\nfunc fixPublisherIDforTagReleases(x *xorm.Engine) error {\n\ttype Release struct {\n\t\tID int64\n\t\tRepoID int64\n\t\tSha1 string\n\t\tTagName string\n\t\tPublisherID int64\n\t}\n\n\ttype Repository struct {\n\t\tID int64\n\t\tOwnerID int64\n\t\tOwnerName string\n\t\tName string\n\t}\n\n\ttype User struct {\n\t\tID int64\n\t\tName string\n\t\tEmail string\n\t}\n\n\tconst batchSize = 100\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\n\tvar (\n\t\trepo *Repository\n\t\tgitRepo *git.Repository\n\t\tuser *User\n\t)\n\tdefer func() {\n\t\tif gitRepo != nil {\n\t\t\tgitRepo.Close()\n\t\t}\n\t}()\n\tfor start := 0; ; start += batchSize {\n\t\treleases := make([]*Release, 0, batchSize)\n\n\t\tif err := sess.Begin(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := sess.Limit(batchSize, start).\n\t\t\tWhere(\"publisher_id = 0 OR publisher_id is null\").\n\t\t\tAsc(\"repo_id\", \"id\").Where(\"is_tag=?\", true).\n\t\t\tFind(&releases); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(releases) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tfor _, release := range releases {\n\t\t\tif repo == nil || repo.ID != release.RepoID {\n\t\t\t\tif gitRepo != nil {\n\t\t\t\t\tgitRepo.Close()\n\t\t\t\t\tgitRepo = nil\n\t\t\t\t}\n\t\t\t\trepo = new(Repository)\n\t\t\t\thas, err := sess.ID(release.RepoID).Get(repo)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t} else if !has {\n\t\t\t\t\tlog.Warn(\"Release[%d] is orphaned and refers to non-existing repository %d\", release.ID, release.RepoID)\n\t\t\t\t\tlog.Warn(\"This release should be deleted\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif repo.OwnerName == \"\" {\n\t\t\t\t\t\/\/ v120.go migration may not have been run correctly - we'll just replicate it here\n\t\t\t\t\t\/\/ because this appears to be a common-ish problem.\n\t\t\t\t\tif _, err := sess.Exec(\"UPDATE repository SET owner_name = (SELECT name FROM `user` WHERE `user`.id = repository.owner_id)\"); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\tif _, err := sess.ID(release.RepoID).Get(repo); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgitRepo, err = git.OpenRepository(repoPath(repo.OwnerName, repo.Name))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcommit, err := gitRepo.GetTagCommit(release.TagName)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"GetTagCommit: %v\", err)\n\t\t\t}\n\n\t\t\tif user == nil || !strings.EqualFold(user.Email, commit.Author.Email) {\n\t\t\t\tuser = new(User)\n\t\t\t\t_, err = sess.Where(\"email=?\", commit.Author.Email).Get(user)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tuser.Email = commit.Author.Email\n\t\t\t}\n\n\t\t\tif user.ID <= 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trelease.PublisherID = user.ID\n\t\t\tif _, err := sess.ID(release.ID).Cols(\"publisher_id\").Update(release); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif gitRepo != nil {\n\t\t\tgitRepo.Close()\n\t\t}\n\n\t\tif err := sess.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\nPrevent migration 156 failure if tag commit missing (#15519)\/\/ Copyright 2020 The Gitea Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage migrations\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"code.gitea.io\/gitea\/modules\/git\"\n\t\"code.gitea.io\/gitea\/modules\/log\"\n\t\"code.gitea.io\/gitea\/modules\/setting\"\n\n\t\"xorm.io\/xorm\"\n)\n\n\/\/ Copy paste from models\/repo.go because we cannot import models package\nfunc repoPath(userName, repoName string) string {\n\treturn filepath.Join(userPath(userName), strings.ToLower(repoName)+\".git\")\n}\n\nfunc userPath(userName string) string {\n\treturn filepath.Join(setting.RepoRootPath, strings.ToLower(userName))\n}\n\nfunc fixPublisherIDforTagReleases(x *xorm.Engine) error {\n\ttype Release struct {\n\t\tID int64\n\t\tRepoID int64\n\t\tSha1 string\n\t\tTagName string\n\t\tPublisherID int64\n\t}\n\n\ttype Repository struct {\n\t\tID int64\n\t\tOwnerID int64\n\t\tOwnerName string\n\t\tName string\n\t}\n\n\ttype User struct {\n\t\tID int64\n\t\tName string\n\t\tEmail string\n\t}\n\n\tconst batchSize = 100\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\n\tvar (\n\t\trepo *Repository\n\t\tgitRepo *git.Repository\n\t\tuser *User\n\t)\n\tdefer func() {\n\t\tif gitRepo != nil {\n\t\t\tgitRepo.Close()\n\t\t}\n\t}()\n\tfor start := 0; ; start += batchSize {\n\t\treleases := make([]*Release, 0, batchSize)\n\n\t\tif err := sess.Begin(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := sess.Limit(batchSize, start).\n\t\t\tWhere(\"publisher_id = 0 OR publisher_id is null\").\n\t\t\tAsc(\"repo_id\", \"id\").Where(\"is_tag=?\", true).\n\t\t\tFind(&releases); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(releases) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tfor _, release := range releases {\n\t\t\tif repo == nil || repo.ID != release.RepoID {\n\t\t\t\tif gitRepo != nil {\n\t\t\t\t\tgitRepo.Close()\n\t\t\t\t\tgitRepo = nil\n\t\t\t\t}\n\t\t\t\trepo = new(Repository)\n\t\t\t\thas, err := sess.ID(release.RepoID).Get(repo)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"Error whilst loading repository[%d] for release[%d] with tag name %s\", release.RepoID, release.ID, release.TagName)\n\t\t\t\t\treturn err\n\t\t\t\t} else if !has {\n\t\t\t\t\tlog.Warn(\"Release[%d] is orphaned and refers to non-existing repository %d\", release.ID, release.RepoID)\n\t\t\t\t\tlog.Warn(\"This release should be deleted\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif repo.OwnerName == \"\" {\n\t\t\t\t\t\/\/ v120.go migration may not have been run correctly - we'll just replicate it here\n\t\t\t\t\t\/\/ because this appears to be a common-ish problem.\n\t\t\t\t\tif _, err := sess.Exec(\"UPDATE repository SET owner_name = (SELECT name FROM `user` WHERE `user`.id = repository.owner_id)\"); err != nil {\n\t\t\t\t\t\tlog.Error(\"Error whilst updating repository[%d] owner name\", repo.ID)\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\tif _, err := sess.ID(release.RepoID).Get(repo); err != nil {\n\t\t\t\t\t\tlog.Error(\"Error whilst loading repository[%d] for release[%d] with tag name %s\", release.RepoID, release.ID, release.TagName)\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgitRepo, err = git.OpenRepository(repoPath(repo.OwnerName, repo.Name))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"Error whilst opening git repo for %-v\", repo)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcommit, err := gitRepo.GetTagCommit(release.TagName)\n\t\t\tif err != nil {\n\t\t\t\tif git.IsErrNotExist(err) {\n\t\t\t\t\tlog.Warn(\"Unable to find commit %s for Tag: %s in %-v. Cannot update publisher ID.\", err.(*git.ErrNotExist).ID, release.TagName, repo)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlog.Error(\"Error whilst getting commit for Tag: %s in %-v.\", release.TagName, repo)\n\t\t\t\treturn fmt.Errorf(\"GetTagCommit: %v\", err)\n\t\t\t}\n\n\t\t\tif user == nil || !strings.EqualFold(user.Email, commit.Author.Email) {\n\t\t\t\tuser = new(User)\n\t\t\t\t_, err = sess.Where(\"email=?\", commit.Author.Email).Get(user)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"Error whilst getting commit author by email: %s for Tag: %s in %-v.\", commit.Author.Email, release.TagName, repo)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tuser.Email = commit.Author.Email\n\t\t\t}\n\n\t\t\tif user.ID <= 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trelease.PublisherID = user.ID\n\t\t\tif _, err := sess.ID(release.ID).Cols(\"publisher_id\").Update(release); err != nil {\n\t\t\t\tlog.Error(\"Error whilst updating publisher[%d] for release[%d] with tag name %s\", release.PublisherID, release.ID, release.TagName)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif gitRepo != nil {\n\t\t\tgitRepo.Close()\n\t\t}\n\n\t\tif err := sess.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage disk\n\nimport (\n\t\"os\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com\/pingcap\/check\"\n\t\"github.com\/pingcap\/tidb\/config\"\n)\n\nfunc TestT(t *testing.T) {\n\tcheck.TestingT(t)\n}\n\nvar _ = check.SerialSuites(&testDiskSerialSuite{})\n\ntype testDiskSerialSuite struct {\n}\n\nfunc (s *testDiskSerialSuite) TestRemoveDir(c *check.C) {\n\terr := CheckAndInitTempDir()\n\tc.Assert(err, check.IsNil)\n\tc.Assert(checkTempDirExist(), check.Equals, true)\n\tc.Assert(os.RemoveAll(config.GetGlobalConfig().TempStoragePath), check.IsNil)\n\tc.Assert(checkTempDirExist(), check.Equals, false)\n\twg := sync.WaitGroup{}\n\tfor i := 0; i < 10; i++ {\n\t\twg.Add(1)\n\t\tgo func(c *check.C) {\n\t\t\terr := CheckAndInitTempDir()\n\t\t\tc.Assert(err, check.IsNil)\n\t\t\twg.Done()\n\t\t}(c)\n\t}\n\twg.Wait()\n\terr = CheckAndInitTempDir()\n\tc.Assert(err, check.IsNil)\n\tc.Assert(checkTempDirExist(), check.Equals, true)\n}\nexecutor: fix unstable test Issue16696 (#22009)\/\/ Copyright 2020 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage disk\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com\/pingcap\/check\"\n\t\"github.com\/pingcap\/tidb\/config\"\n)\n\nfunc TestT(t *testing.T) {\n\tpath, _ := ioutil.TempDir(\"\", \"tmp-storage-disk-pkg\")\n\tconfig.UpdateGlobal(func(conf *config.Config) {\n\t\tconf.TempStoragePath = path\n\t})\n\t_ = os.RemoveAll(path) \/\/ clean the uncleared temp file during the last run.\n\t_ = os.MkdirAll(path, 0755)\n\tcheck.TestingT(t)\n}\n\nvar _ = check.SerialSuites(&testDiskSerialSuite{})\n\ntype testDiskSerialSuite struct {\n}\n\nfunc (s *testDiskSerialSuite) TestRemoveDir(c *check.C) {\n\terr := CheckAndInitTempDir()\n\tc.Assert(err, check.IsNil)\n\tc.Assert(checkTempDirExist(), check.Equals, true)\n\tc.Assert(os.RemoveAll(config.GetGlobalConfig().TempStoragePath), check.IsNil)\n\tc.Assert(checkTempDirExist(), check.Equals, false)\n\twg := sync.WaitGroup{}\n\tfor i := 0; i < 10; i++ {\n\t\twg.Add(1)\n\t\tgo func(c *check.C) {\n\t\t\terr := CheckAndInitTempDir()\n\t\t\tc.Assert(err, check.IsNil)\n\t\t\twg.Done()\n\t\t}(c)\n\t}\n\twg.Wait()\n\terr = CheckAndInitTempDir()\n\tc.Assert(err, check.IsNil)\n\tc.Assert(checkTempDirExist(), check.Equals, true)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2021 The Gitea Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage migrations\n\nimport (\n\t\"code.gitea.io\/gitea\/models\"\n\t\"code.gitea.io\/gitea\/modules\/migrations\/base\"\n\t\"code.gitea.io\/gitea\/modules\/structs\"\n\t\"code.gitea.io\/gitea\/modules\/util\"\n\n\tjsoniter \"github.com\/json-iterator\/go\"\n\t\"xorm.io\/builder\"\n\t\"xorm.io\/xorm\"\n)\n\nfunc deleteMigrationCredentials(x *xorm.Engine) (err error) {\n\tconst batchSize = 100\n\n\t\/\/ only match migration tasks, that are not pending or running\n\tcond := builder.Eq{\n\t\t\"type\": structs.TaskTypeMigrateRepo,\n\t}.And(builder.Gte{\n\t\t\"status\": structs.TaskStatusStopped,\n\t})\n\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\n\tfor start := 0; ; start += batchSize {\n\t\ttasks := make([]*models.Task, 0, batchSize)\n\t\tif err = sess.Limit(batchSize, start).Where(cond, 0).Find(&tasks); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif len(tasks) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif err = sess.Begin(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tfor _, t := range tasks {\n\t\t\tif t.PayloadContent, err = removeCredentials(t.PayloadContent); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err = sess.ID(t.ID).Cols(\"payload_content\").Update(t); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = sess.Commit(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc removeCredentials(payload string) (string, error) {\n\tvar opts base.MigrateOptions\n\tjson := jsoniter.ConfigCompatibleWithStandardLibrary\n\terr := json.Unmarshal([]byte(payload), &opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\topts.AuthPassword = \"\"\n\topts.AuthToken = \"\"\n\topts.CloneAddr = util.NewStringURLSanitizer(opts.CloneAddr, true).Replace(opts.CloneAddr)\n\n\tconfBytes, err := json.Marshal(opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(confBytes), nil\n}\nv180 migration should be standalone (#16151)\/\/ Copyright 2021 The Gitea Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage migrations\n\nimport (\n\t\"code.gitea.io\/gitea\/modules\/util\"\n\n\tjsoniter \"github.com\/json-iterator\/go\"\n\t\"xorm.io\/builder\"\n\t\"xorm.io\/xorm\"\n)\n\nfunc deleteMigrationCredentials(x *xorm.Engine) (err error) {\n\t\/\/ Task represents a task\n\ttype Task struct {\n\t\tID int64\n\t\tDoerID int64 `xorm:\"index\"` \/\/ operator\n\t\tOwnerID int64 `xorm:\"index\"` \/\/ repo owner id, when creating, the repoID maybe zero\n\t\tRepoID int64 `xorm:\"index\"`\n\t\tType int\n\t\tStatus int `xorm:\"index\"`\n\t\tStartTime int64\n\t\tEndTime int64\n\t\tPayloadContent string `xorm:\"TEXT\"`\n\t\tErrors string `xorm:\"TEXT\"` \/\/ if task failed, saved the error reason\n\t\tCreated int64 `xorm:\"created\"`\n\t}\n\n\tconst TaskTypeMigrateRepo = 0\n\tconst TaskStatusStopped = 2\n\n\tconst batchSize = 100\n\n\t\/\/ only match migration tasks, that are not pending or running\n\tcond := builder.Eq{\n\t\t\"type\": TaskTypeMigrateRepo,\n\t}.And(builder.Gte{\n\t\t\"status\": TaskStatusStopped,\n\t})\n\n\tsess := x.NewSession()\n\tdefer sess.Close()\n\n\tfor start := 0; ; start += batchSize {\n\t\ttasks := make([]*Task, 0, batchSize)\n\t\tif err = sess.Limit(batchSize, start).Where(cond, 0).Find(&tasks); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif len(tasks) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif err = sess.Begin(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tfor _, t := range tasks {\n\t\t\tif t.PayloadContent, err = removeCredentials(t.PayloadContent); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err = sess.ID(t.ID).Cols(\"payload_content\").Update(t); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = sess.Commit(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc removeCredentials(payload string) (string, error) {\n\t\/\/ MigrateOptions defines the way a repository gets migrated\n\t\/\/ this is for internal usage by migrations module and func who interact with it\n\ttype MigrateOptions struct {\n\t\t\/\/ required: true\n\t\tCloneAddr string `json:\"clone_addr\" binding:\"Required\"`\n\t\tCloneAddrEncrypted string `json:\"clone_addr_encrypted,omitempty\"`\n\t\tAuthUsername string `json:\"auth_username\"`\n\t\tAuthPassword string `json:\"-\"`\n\t\tAuthPasswordEncrypted string `json:\"auth_password_encrypted,omitempty\"`\n\t\tAuthToken string `json:\"-\"`\n\t\tAuthTokenEncrypted string `json:\"auth_token_encrypted,omitempty\"`\n\t\t\/\/ required: true\n\t\tUID int `json:\"uid\" binding:\"Required\"`\n\t\t\/\/ required: true\n\t\tRepoName string `json:\"repo_name\" binding:\"Required\"`\n\t\tMirror bool `json:\"mirror\"`\n\t\tLFS bool `json:\"lfs\"`\n\t\tLFSEndpoint string `json:\"lfs_endpoint\"`\n\t\tPrivate bool `json:\"private\"`\n\t\tDescription string `json:\"description\"`\n\t\tOriginalURL string\n\t\tGitServiceType int\n\t\tWiki bool\n\t\tIssues bool\n\t\tMilestones bool\n\t\tLabels bool\n\t\tReleases bool\n\t\tComments bool\n\t\tPullRequests bool\n\t\tReleaseAssets bool\n\t\tMigrateToRepoID int64\n\t\tMirrorInterval string `json:\"mirror_interval\"`\n\t}\n\n\tvar opts MigrateOptions\n\tjson := jsoniter.ConfigCompatibleWithStandardLibrary\n\terr := json.Unmarshal([]byte(payload), &opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\topts.AuthPassword = \"\"\n\topts.AuthToken = \"\"\n\topts.CloneAddr = util.NewStringURLSanitizer(opts.CloneAddr, true).Replace(opts.CloneAddr)\n\n\tconfBytes, err := json.Marshal(opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(confBytes), nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage manager\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\n\tdclient \"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/google\/cadvisor\/container\/docker\"\n\t\"github.com\/google\/cadvisor\/fs\"\n\t\"github.com\/google\/cadvisor\/info\"\n\t\"github.com\/google\/cadvisor\/utils\"\n\t\"github.com\/google\/cadvisor\/utils\/sysfs\"\n\t\"github.com\/google\/cadvisor\/utils\/sysinfo\"\n)\n\nvar cpuRegExp = regexp.MustCompile(\"processor\\\\t*: +([0-9]+)\")\nvar coreRegExp = regexp.MustCompile(\"core id\\\\t*: +([0-9]+)\")\nvar nodeRegExp = regexp.MustCompile(\"physical id\\\\t*: +([0-9]+)\")\nvar CpuClockSpeedMHz = regexp.MustCompile(\"cpu MHz\\\\t*: +([0-9]+.[0-9]+)\")\nvar memoryCapacityRegexp = regexp.MustCompile(\"MemTotal: *([0-9]+) kB\")\n\nfunc getClockSpeed(procInfo []byte) (uint64, error) {\n\t\/\/ First look through sys to find a max supported cpu frequency.\n\tconst maxFreqFile = \"\/sys\/devices\/system\/cpu\/cpu0\/cpufreq\/cpuinfo_max_freq\"\n\tif utils.FileExists(maxFreqFile) {\n\t\tval, err := ioutil.ReadFile(maxFreqFile)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tvar maxFreq uint64\n\t\tn, err := fmt.Sscanf(string(val), \"%d\", &maxFreq)\n\t\tif err != nil || n != 1 {\n\t\t\treturn 0, fmt.Errorf(\"could not parse frequency %q\", val)\n\t\t}\n\t\treturn maxFreq, nil\n\t}\n\t\/\/ Fall back to \/proc\/cpuinfo\n\tmatches := CpuClockSpeedMHz.FindSubmatch(procInfo)\n\tif len(matches) != 2 {\n\t\treturn 0, fmt.Errorf(\"could not detect clock speed from output: %q\", string(procInfo))\n\t}\n\tspeed, err := strconv.ParseFloat(string(matches[1]), 64)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t\/\/ Convert to kHz\n\treturn uint64(speed * 1000), nil\n}\n\nfunc getMemoryCapacity(b []byte) (int64, error) {\n\tmatches := memoryCapacityRegexp.FindSubmatch(b)\n\tif len(matches) != 2 {\n\t\treturn -1, fmt.Errorf(\"failed to find memory capacity in output: %q\", string(b))\n\t}\n\tm, err := strconv.ParseInt(string(matches[1]), 10, 64)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\t\/\/ Convert to bytes.\n\treturn m * 1024, err\n}\n\nfunc extractValue(s string, r *regexp.Regexp) (bool, int, error) {\n\tmatches := r.FindSubmatch([]byte(s))\n\tif len(matches) == 2 {\n\t\tval, err := strconv.ParseInt(string(matches[1]), 10, 32)\n\t\tif err != nil {\n\t\t\treturn true, -1, err\n\t\t}\n\t\treturn true, int(val), nil\n\t}\n\treturn false, -1, nil\n}\n\nfunc findNode(nodes []info.Node, id int) (bool, int) {\n\tfor i, n := range nodes {\n\t\tif n.Id == id {\n\t\t\treturn true, i\n\t\t}\n\t}\n\treturn false, -1\n}\n\nfunc addNode(nodes *[]info.Node, id int) (int, error) {\n\tvar idx int\n\tif id == -1 {\n\t\t\/\/ Some VMs don't fill topology data. Export single package.\n\t\tid = 0\n\t}\n\n\tok, idx := findNode(*nodes, id)\n\tif !ok {\n\t\t\/\/ New node\n\t\tnode := info.Node{Id: id}\n\t\t\/\/ Add per-node memory information.\n\t\tmeminfo := fmt.Sprintf(\"\/sys\/devices\/system\/node\/node%d\/meminfo\", id)\n\t\tout, err := ioutil.ReadFile(meminfo)\n\t\t\/\/ Ignore if per-node info is not available.\n\t\tif err == nil {\n\t\t\tm, err := getMemoryCapacity(out)\n\t\t\tif err != nil {\n\t\t\t\treturn -1, err\n\t\t\t}\n\t\t\tnode.Memory = uint64(m)\n\t\t}\n\t\t*nodes = append(*nodes, node)\n\t\tidx = len(*nodes) - 1\n\t}\n\treturn idx, nil\n}\n\nfunc getTopology(sysFs sysfs.SysFs, cpuinfo string) ([]info.Node, int, error) {\n\tnodes := []info.Node{}\n\tnumCores := 0\n\tlastThread := -1\n\tlastCore := -1\n\tlastNode := -1\n\tfor _, line := range strings.Split(cpuinfo, \"\\n\") {\n\t\tok, val, err := extractValue(line, cpuRegExp)\n\t\tif err != nil {\n\t\t\treturn nil, -1, fmt.Errorf(\"could not parse cpu info from %q: %v\", line, err)\n\t\t}\n\t\tif ok {\n\t\t\tthread := val\n\t\t\tnumCores++\n\t\t\tif lastThread != -1 {\n\t\t\t\t\/\/ New cpu section. Save last one.\n\t\t\t\tnodeIdx, err := addNode(&nodes, lastNode)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, -1, fmt.Errorf(\"failed to add node %d: %v\", lastNode, err)\n\t\t\t\t}\n\t\t\t\tnodes[nodeIdx].AddThread(lastThread, lastCore)\n\t\t\t\tlastCore = -1\n\t\t\t\tlastNode = -1\n\t\t\t}\n\t\t\tlastThread = thread\n\t\t}\n\t\tok, val, err = extractValue(line, coreRegExp)\n\t\tif err != nil {\n\t\t\treturn nil, -1, fmt.Errorf(\"could not parse core info from %q: %v\", line, err)\n\t\t}\n\t\tif ok {\n\t\t\tlastCore = val\n\t\t}\n\t\tok, val, err = extractValue(line, nodeRegExp)\n\t\tif err != nil {\n\t\t\treturn nil, -1, fmt.Errorf(\"could not parse node info from %q: %v\", line, err)\n\t\t}\n\t\tif ok {\n\t\t\tlastNode = val\n\t\t}\n\t}\n\tnodeIdx, err := addNode(&nodes, lastNode)\n\tif err != nil {\n\t\treturn nil, -1, fmt.Errorf(\"failed to add node %d: %v\", lastNode, err)\n\t}\n\tnodes[nodeIdx].AddThread(lastThread, lastCore)\n\tif numCores < 1 {\n\t\treturn nil, numCores, fmt.Errorf(\"could not detect any cores\")\n\t}\n\tfor idx, node := range nodes {\n\t\tcaches, err := sysinfo.GetCacheInfo(sysFs, node.Cores[0].Id)\n\t\tif err != nil {\n\t\t\treturn nil, -1, fmt.Errorf(\"failed to get cache information for node %d: %v\", node.Id, err)\n\t\t}\n\t\tnumThreadsPerCore := len(node.Cores[0].Threads)\n\t\tnumThreadsPerNode := len(node.Cores) * numThreadsPerCore\n\t\tfor _, cache := range caches {\n\t\t\tc := info.Cache{\n\t\t\t\tSize: cache.Size,\n\t\t\t\tLevel: cache.Level,\n\t\t\t\tType: cache.Type,\n\t\t\t}\n\t\t\tif cache.Cpus == numThreadsPerNode && cache.Level > 2 {\n\t\t\t\t\/\/ Add a node-level cache.\n\t\t\t\tnodes[idx].AddNodeCache(c)\n\t\t\t} else if cache.Cpus == numThreadsPerCore {\n\t\t\t\t\/\/ Add to each core.\n\t\t\t\tnodes[idx].AddPerCoreCache(c)\n\t\t\t}\n\t\t\t\/\/ Ignore unknown caches.\n\t\t}\n\t}\n\treturn nodes, numCores, nil\n}\n\nfunc getMachineInfo(sysFs sysfs.SysFs) (*info.MachineInfo, error) {\n\tcpuinfo, err := ioutil.ReadFile(\"\/proc\/cpuinfo\")\n\tclockSpeed, err := getClockSpeed(cpuinfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get the amount of usable memory from \/proc\/meminfo.\n\tout, err := ioutil.ReadFile(\"\/proc\/meminfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmemoryCapacity, err := getMemoryCapacity(out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfsInfo, err := fs.NewFsInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfilesystems, err := fsInfo.GetGlobalFsInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdiskMap, err := sysinfo.GetBlockDeviceInfo(sysFs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnetDevices, err := sysinfo.GetNetworkDevices(sysFs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttopology, numCores, err := getTopology(sysFs, string(cpuinfo))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmachineInfo := &info.MachineInfo{\n\t\tNumCores: numCores,\n\t\tCpuFrequency: clockSpeed,\n\t\tMemoryCapacity: memoryCapacity,\n\t\tDiskMap: diskMap,\n\t\tNetworkDevices: netDevices,\n\t\tTopology: topology,\n\t}\n\n\tfor _, fs := range filesystems {\n\t\tmachineInfo.Filesystems = append(machineInfo.Filesystems, info.FsInfo{fs.Device, fs.Capacity})\n\t}\n\n\treturn machineInfo, nil\n}\n\nfunc getVersionInfo() (*info.VersionInfo, error) {\n\n\tkernel_version := getKernelVersion()\n\tcontainer_os := getContainerOsVersion()\n\tdocker_version := getDockerVersion()\n\n\treturn &info.VersionInfo{\n\t\tKernelVersion: kernel_version,\n\t\tContainerOsVersion: container_os,\n\t\tDockerVersion: docker_version,\n\t\tCadvisorVersion: info.VERSION,\n\t}, nil\n}\n\nfunc getContainerOsVersion() string {\n\tcontainer_os := \"Unknown\"\n\tos_release, err := ioutil.ReadFile(\"\/etc\/os-release\")\n\tif err == nil {\n\t\t\/\/ We might be running in a busybox or some hand-crafted image.\n\t\t\/\/ It's useful to know why cadvisor didn't come up.\n\t\tfor _, line := range strings.Split(string(os_release), \"\\n\") {\n\t\t\tparsed := strings.Split(line, \"\\\"\")\n\t\t\tif len(parsed) == 3 && parsed[0] == \"PRETTY_NAME=\" {\n\t\t\t\tcontainer_os = parsed[1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn container_os\n}\n\nfunc getDockerVersion() string {\n\tdocker_version := \"Unknown\"\n\tclient, err := dclient.NewClient(*docker.ArgDockerEndpoint)\n\tif err == nil {\n\t\tversion, err := client.Version()\n\t\tif err == nil {\n\t\t\tdocker_version = version.Get(\"Version\")\n\t\t}\n\t}\n\treturn docker_version\n}\n\nfunc getKernelVersion() string {\n\tuname := &syscall.Utsname{}\n\n\tif err := syscall.Uname(uname); err != nil {\n\t\treturn \"Unknown\"\n\t}\n\n\trelease := make([]byte, len(uname.Release))\n\ti := 0\n\tfor _, c := range uname.Release {\n\t\trelease[i] = byte(c)\n\t\ti++\n\t}\n\trelease = release[:bytes.IndexByte(release, 0)]\n\n\treturn string(release)\n}\nFix reading cache info for machines with unused packages.\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage manager\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\n\tdclient \"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/google\/cadvisor\/container\/docker\"\n\t\"github.com\/google\/cadvisor\/fs\"\n\t\"github.com\/google\/cadvisor\/info\"\n\t\"github.com\/google\/cadvisor\/utils\"\n\t\"github.com\/google\/cadvisor\/utils\/sysfs\"\n\t\"github.com\/google\/cadvisor\/utils\/sysinfo\"\n)\n\nvar cpuRegExp = regexp.MustCompile(\"processor\\\\t*: +([0-9]+)\")\nvar coreRegExp = regexp.MustCompile(\"core id\\\\t*: +([0-9]+)\")\nvar nodeRegExp = regexp.MustCompile(\"physical id\\\\t*: +([0-9]+)\")\nvar CpuClockSpeedMHz = regexp.MustCompile(\"cpu MHz\\\\t*: +([0-9]+.[0-9]+)\")\nvar memoryCapacityRegexp = regexp.MustCompile(\"MemTotal: *([0-9]+) kB\")\n\nfunc getClockSpeed(procInfo []byte) (uint64, error) {\n\t\/\/ First look through sys to find a max supported cpu frequency.\n\tconst maxFreqFile = \"\/sys\/devices\/system\/cpu\/cpu0\/cpufreq\/cpuinfo_max_freq\"\n\tif utils.FileExists(maxFreqFile) {\n\t\tval, err := ioutil.ReadFile(maxFreqFile)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tvar maxFreq uint64\n\t\tn, err := fmt.Sscanf(string(val), \"%d\", &maxFreq)\n\t\tif err != nil || n != 1 {\n\t\t\treturn 0, fmt.Errorf(\"could not parse frequency %q\", val)\n\t\t}\n\t\treturn maxFreq, nil\n\t}\n\t\/\/ Fall back to \/proc\/cpuinfo\n\tmatches := CpuClockSpeedMHz.FindSubmatch(procInfo)\n\tif len(matches) != 2 {\n\t\treturn 0, fmt.Errorf(\"could not detect clock speed from output: %q\", string(procInfo))\n\t}\n\tspeed, err := strconv.ParseFloat(string(matches[1]), 64)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t\/\/ Convert to kHz\n\treturn uint64(speed * 1000), nil\n}\n\nfunc getMemoryCapacity(b []byte) (int64, error) {\n\tmatches := memoryCapacityRegexp.FindSubmatch(b)\n\tif len(matches) != 2 {\n\t\treturn -1, fmt.Errorf(\"failed to find memory capacity in output: %q\", string(b))\n\t}\n\tm, err := strconv.ParseInt(string(matches[1]), 10, 64)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\t\/\/ Convert to bytes.\n\treturn m * 1024, err\n}\n\nfunc extractValue(s string, r *regexp.Regexp) (bool, int, error) {\n\tmatches := r.FindSubmatch([]byte(s))\n\tif len(matches) == 2 {\n\t\tval, err := strconv.ParseInt(string(matches[1]), 10, 32)\n\t\tif err != nil {\n\t\t\treturn true, -1, err\n\t\t}\n\t\treturn true, int(val), nil\n\t}\n\treturn false, -1, nil\n}\n\nfunc findNode(nodes []info.Node, id int) (bool, int) {\n\tfor i, n := range nodes {\n\t\tif n.Id == id {\n\t\t\treturn true, i\n\t\t}\n\t}\n\treturn false, -1\n}\n\nfunc addNode(nodes *[]info.Node, id int) (int, error) {\n\tvar idx int\n\tif id == -1 {\n\t\t\/\/ Some VMs don't fill topology data. Export single package.\n\t\tid = 0\n\t}\n\n\tok, idx := findNode(*nodes, id)\n\tif !ok {\n\t\t\/\/ New node\n\t\tnode := info.Node{Id: id}\n\t\t\/\/ Add per-node memory information.\n\t\tmeminfo := fmt.Sprintf(\"\/sys\/devices\/system\/node\/node%d\/meminfo\", id)\n\t\tout, err := ioutil.ReadFile(meminfo)\n\t\t\/\/ Ignore if per-node info is not available.\n\t\tif err == nil {\n\t\t\tm, err := getMemoryCapacity(out)\n\t\t\tif err != nil {\n\t\t\t\treturn -1, err\n\t\t\t}\n\t\t\tnode.Memory = uint64(m)\n\t\t}\n\t\t*nodes = append(*nodes, node)\n\t\tidx = len(*nodes) - 1\n\t}\n\treturn idx, nil\n}\n\nfunc getTopology(sysFs sysfs.SysFs, cpuinfo string) ([]info.Node, int, error) {\n\tnodes := []info.Node{}\n\tnumCores := 0\n\tlastThread := -1\n\tlastCore := -1\n\tlastNode := -1\n\tfor _, line := range strings.Split(cpuinfo, \"\\n\") {\n\t\tok, val, err := extractValue(line, cpuRegExp)\n\t\tif err != nil {\n\t\t\treturn nil, -1, fmt.Errorf(\"could not parse cpu info from %q: %v\", line, err)\n\t\t}\n\t\tif ok {\n\t\t\tthread := val\n\t\t\tnumCores++\n\t\t\tif lastThread != -1 {\n\t\t\t\t\/\/ New cpu section. Save last one.\n\t\t\t\tnodeIdx, err := addNode(&nodes, lastNode)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, -1, fmt.Errorf(\"failed to add node %d: %v\", lastNode, err)\n\t\t\t\t}\n\t\t\t\tnodes[nodeIdx].AddThread(lastThread, lastCore)\n\t\t\t\tlastCore = -1\n\t\t\t\tlastNode = -1\n\t\t\t}\n\t\t\tlastThread = thread\n\t\t}\n\t\tok, val, err = extractValue(line, coreRegExp)\n\t\tif err != nil {\n\t\t\treturn nil, -1, fmt.Errorf(\"could not parse core info from %q: %v\", line, err)\n\t\t}\n\t\tif ok {\n\t\t\tlastCore = val\n\t\t}\n\t\tok, val, err = extractValue(line, nodeRegExp)\n\t\tif err != nil {\n\t\t\treturn nil, -1, fmt.Errorf(\"could not parse node info from %q: %v\", line, err)\n\t\t}\n\t\tif ok {\n\t\t\tlastNode = val\n\t\t}\n\t}\n\tnodeIdx, err := addNode(&nodes, lastNode)\n\tif err != nil {\n\t\treturn nil, -1, fmt.Errorf(\"failed to add node %d: %v\", lastNode, err)\n\t}\n\tnodes[nodeIdx].AddThread(lastThread, lastCore)\n\tif numCores < 1 {\n\t\treturn nil, numCores, fmt.Errorf(\"could not detect any cores\")\n\t}\n\tfor idx, node := range nodes {\n\t\tcaches, err := sysinfo.GetCacheInfo(sysFs, node.Cores[0].Threads[0])\n\t\tif err != nil {\n\t\t\treturn nil, -1, fmt.Errorf(\"failed to get cache information for node %d: %v\", node.Id, err)\n\t\t}\n\t\tnumThreadsPerCore := len(node.Cores[0].Threads)\n\t\tnumThreadsPerNode := len(node.Cores) * numThreadsPerCore\n\t\tfor _, cache := range caches {\n\t\t\tc := info.Cache{\n\t\t\t\tSize: cache.Size,\n\t\t\t\tLevel: cache.Level,\n\t\t\t\tType: cache.Type,\n\t\t\t}\n\t\t\tif cache.Cpus == numThreadsPerNode && cache.Level > 2 {\n\t\t\t\t\/\/ Add a node-level cache.\n\t\t\t\tnodes[idx].AddNodeCache(c)\n\t\t\t} else if cache.Cpus == numThreadsPerCore {\n\t\t\t\t\/\/ Add to each core.\n\t\t\t\tnodes[idx].AddPerCoreCache(c)\n\t\t\t}\n\t\t\t\/\/ Ignore unknown caches.\n\t\t}\n\t}\n\treturn nodes, numCores, nil\n}\n\nfunc getMachineInfo(sysFs sysfs.SysFs) (*info.MachineInfo, error) {\n\tcpuinfo, err := ioutil.ReadFile(\"\/proc\/cpuinfo\")\n\tclockSpeed, err := getClockSpeed(cpuinfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get the amount of usable memory from \/proc\/meminfo.\n\tout, err := ioutil.ReadFile(\"\/proc\/meminfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmemoryCapacity, err := getMemoryCapacity(out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfsInfo, err := fs.NewFsInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfilesystems, err := fsInfo.GetGlobalFsInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdiskMap, err := sysinfo.GetBlockDeviceInfo(sysFs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnetDevices, err := sysinfo.GetNetworkDevices(sysFs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttopology, numCores, err := getTopology(sysFs, string(cpuinfo))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmachineInfo := &info.MachineInfo{\n\t\tNumCores: numCores,\n\t\tCpuFrequency: clockSpeed,\n\t\tMemoryCapacity: memoryCapacity,\n\t\tDiskMap: diskMap,\n\t\tNetworkDevices: netDevices,\n\t\tTopology: topology,\n\t}\n\n\tfor _, fs := range filesystems {\n\t\tmachineInfo.Filesystems = append(machineInfo.Filesystems, info.FsInfo{fs.Device, fs.Capacity})\n\t}\n\n\treturn machineInfo, nil\n}\n\nfunc getVersionInfo() (*info.VersionInfo, error) {\n\n\tkernel_version := getKernelVersion()\n\tcontainer_os := getContainerOsVersion()\n\tdocker_version := getDockerVersion()\n\n\treturn &info.VersionInfo{\n\t\tKernelVersion: kernel_version,\n\t\tContainerOsVersion: container_os,\n\t\tDockerVersion: docker_version,\n\t\tCadvisorVersion: info.VERSION,\n\t}, nil\n}\n\nfunc getContainerOsVersion() string {\n\tcontainer_os := \"Unknown\"\n\tos_release, err := ioutil.ReadFile(\"\/etc\/os-release\")\n\tif err == nil {\n\t\t\/\/ We might be running in a busybox or some hand-crafted image.\n\t\t\/\/ It's useful to know why cadvisor didn't come up.\n\t\tfor _, line := range strings.Split(string(os_release), \"\\n\") {\n\t\t\tparsed := strings.Split(line, \"\\\"\")\n\t\t\tif len(parsed) == 3 && parsed[0] == \"PRETTY_NAME=\" {\n\t\t\t\tcontainer_os = parsed[1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn container_os\n}\n\nfunc getDockerVersion() string {\n\tdocker_version := \"Unknown\"\n\tclient, err := dclient.NewClient(*docker.ArgDockerEndpoint)\n\tif err == nil {\n\t\tversion, err := client.Version()\n\t\tif err == nil {\n\t\t\tdocker_version = version.Get(\"Version\")\n\t\t}\n\t}\n\treturn docker_version\n}\n\nfunc getKernelVersion() string {\n\tuname := &syscall.Utsname{}\n\n\tif err := syscall.Uname(uname); err != nil {\n\t\treturn \"Unknown\"\n\t}\n\n\trelease := make([]byte, len(uname.Release))\n\ti := 0\n\tfor _, c := range uname.Release {\n\t\trelease[i] = byte(c)\n\t\ti++\n\t}\n\trelease = release[:bytes.IndexByte(release, 0)]\n\n\treturn string(release)\n}\n<|endoftext|>"} {"text":"\/\/ md5 supports MD5 hashes in various formats.\npackage md5\n\nimport (\n\tcryptomd5 \"crypto\/md5\"\n\t\"fmt\"\n\t\"math\/big\"\n\n\t\"github.com\/grokify\/gotilla\/type\/stringsutil\"\n)\n\n\/\/ Md5Base36Length is the length for a MD5 Base36 string\nconst (\n\tmd5Base62Length int = 22\n\tmd5Base62Format string = `%022s`\n\tmd5Base36Length int = 25\n\tmd5Base36Format string = `%025s`\n\tmd5Base10Length int = 39\n\tmd5Base10Format string = `%039s`\n)\n\n\/\/ Md5Base10 returns a Base10 encoded MD5 hash of a string.\nfunc Md5Base10(s string) string {\n\ti := new(big.Int)\n\ti.SetString(fmt.Sprintf(\"%x\", cryptomd5.Sum([]byte(s))), 16)\n\treturn fmt.Sprintf(md5Base10Format, i.String())\n}\n\n\/\/ Md5Base36 returns a Base36 encoded MD5 hash of a string.\nfunc Md5Base36(s string) string {\n\thexVal := fmt.Sprintf(\"%x\", cryptomd5.Sum([]byte(s)))\n\ti := big.NewInt(0)\n\ti2, ok := i.SetString(hexVal, 16)\n\tif !ok {\n\t\tpanic(\"E_CANNOT_CONVERT_HEX\")\n\t}\n\treturn fmt.Sprintf(md5Base36Format, i2.Text(36))\n}\n\n\/\/ Md5Base62 returns a Base62 encoded MD5 hash of a string.\n\/\/ This uses the Golang alphabet [0-9a-zA-Z].\nfunc Md5Base62(s string) string {\n\thexVal := fmt.Sprintf(\"%x\", cryptomd5.Sum([]byte(s)))\n\ti := big.NewInt(0)\n\ti2, ok := i.SetString(hexVal, 16)\n\tif !ok {\n\t\tpanic(\"E_CANNOT_CONVERT_HEX\")\n\t}\n\treturn fmt.Sprintf(md5Base62Format, i2.Text(62))\n}\n\n\/\/ Md5Base62Upper returns a Base62 encoded MD5 hash of a string.\n\/\/ Note Base62 encoding uses the GMP alphabet [0-9A-Za-z] instead\n\/\/ of the Golang alphabet [0-9a-zA-Z] because the GMP alphabet\n\/\/ may be more standard, e.g. used in GMP and follows ASCII\n\/\/ table order.\nfunc Md5Base62UpperFirst(s string) string {\n\thexVal := fmt.Sprintf(\"%x\", cryptomd5.Sum([]byte(s)))\n\ti := big.NewInt(0)\n\ti2, ok := i.SetString(hexVal, 16)\n\tif !ok {\n\t\tpanic(\"E_CANNOT_CONVERT_HEX\")\n\t}\n\treturn fmt.Sprintf(md5Base62Format, stringsutil.ToOpposite(i2.Text(62)))\n}\nstreamline code\/\/ md5 supports MD5 hashes in various formats.\npackage md5\n\nimport (\n\tcryptomd5 \"crypto\/md5\"\n\t\"fmt\"\n\t\"math\/big\"\n\n\t\"github.com\/grokify\/gotilla\/type\/stringsutil\"\n)\n\n\/\/ Md5Base36Length is the length for a MD5 Base36 string\nconst (\n\tmd5Base62Length int = 22\n\tmd5Base62Format string = `%022s`\n\tmd5Base36Length int = 25\n\tmd5Base36Format string = `%025s`\n\tmd5Base10Length int = 39\n\tmd5Base10Format string = `%039s`\n)\n\n\/\/ Md5Base10 returns a Base10 encoded MD5 hash of a string.\nfunc Md5Base10(s string) string {\n\ti := new(big.Int)\n\ti.SetString(fmt.Sprintf(\"%x\", cryptomd5.Sum([]byte(s))), 16)\n\treturn fmt.Sprintf(md5Base10Format, i.String())\n}\n\n\/\/ Md5Base36 returns a Base36 encoded MD5 hash of a string.\nfunc Md5Base36(s string) string {\n\ti := new(big.Int)\n\ti.SetString(fmt.Sprintf(\"%x\", cryptomd5.Sum([]byte(s))), 16)\n\treturn fmt.Sprintf(md5Base36Format, i.Text(36))\n}\n\n\/\/ Md5Base62 returns a Base62 encoded MD5 hash of a string.\n\/\/ This uses the Golang alphabet [0-9a-zA-Z].\nfunc Md5Base62(s string) string {\n\ti := new(big.Int)\n\ti.SetString(fmt.Sprintf(\"%x\", cryptomd5.Sum([]byte(s))), 16)\n\treturn fmt.Sprintf(md5Base62Format, i.Text(62))\n}\n\n\/\/ Md5Base62Upper returns a Base62 encoded MD5 hash of a string.\n\/\/ Note Base62 encoding uses the GMP alphabet [0-9A-Za-z] instead\n\/\/ of the Golang alphabet [0-9a-zA-Z] because the GMP alphabet\n\/\/ may be more standard, e.g. used in GMP and follows ASCII\n\/\/ table order.\nfunc Md5Base62UpperFirst(s string) string {\n\ti := big.NewInt(0)\n\ti2, ok := i.SetString(fmt.Sprintf(\"%x\", cryptomd5.Sum([]byte(s))), 16)\n\tif !ok {\n\t\tpanic(\"E_CANNOT_CONVERT_HEX\")\n\t}\n\treturn fmt.Sprintf(md5Base62Format, stringsutil.ToOpposite(i2.Text(62)))\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar verbose *bool\n\ntype getArgs struct {\n\thostname string\n\tport int\n\tpath string\n\tauth string\n\turls bool\n\tverbose bool\n\ttimeout int\n\tresultChan chan getReply\n}\n\ntype getReply struct {\n\terr interface{}\n\trv bool\n}\n\nfunc vLogger(msg string, args ...interface{}) {\n\n\tif *verbose {\n\t\tfmt.Fprintf(os.Stderr, msg, args...)\n\t}\n\n}\n\nfunc get(request chan *getArgs) {\n\n\tvar err error\n\n\tfor args := range request {\n\n\t\t\/\/ defer func() {\n\t\t\/\/ \tif err := recover(); err != nil {\n\t\t\/\/ \t\targs.resultChan <- getReply{err: err}\n\n\t\t\/\/ \t\t\/\/something bad happened\n\t\t\/\/ \t\treturn\n\t\t\/\/ \t}\n\t\t\/\/ }()\n\n\t\tvLogger(\"fetching:hostname:%s:\\n\", args.hostname)\n\n\t\tres := &http.Response{}\n\n\t\tif args.urls {\n\n\t\t\turl := args.hostname\n\t\t\tres, err = http.Head(url)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\targs.resultChan <- getReply{rv: false, err: err}\n\t\t\t\t_, err = ioutil.ReadAll(res.Body)\n\t\t\t\tres.Body.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, err = ioutil.ReadAll(res.Body)\n\t\t\tres.Body.Close()\n\n\t\t} else {\n\n\t\t\tclient := &http.Client{Timeout: time.Duration(args.timeout) * time.Second}\n\n\t\t\t\/\/ had to allocate this or the SetBasicAuth will panic\n\t\t\theaders := make(map[string][]string)\n\t\t\thostPort := fmt.Sprintf(\"%s:%d\", args.hostname, args.port)\n\n\t\t\tvLogger(\"adding hostPort:%s:%d:path:%s:\\n\", args.hostname, args.port, args.path)\n\n\t\t\treq := &http.Request{\n\t\t\t\tMethod: \"HEAD\",\n\t\t\t\t\/\/ Host: hostPort,\n\t\t\t\tURL: &url.URL{\n\t\t\t\t\tHost: hostPort,\n\t\t\t\t\tScheme: \"http\",\n\t\t\t\t\tOpaque: args.path,\n\t\t\t\t},\n\t\t\t\tHeader: headers,\n\t\t\t}\n\n\t\t\tif args.auth != \"\" {\n\n\t\t\t\tup := strings.SplitN(args.auth, \":\", 2)\n\n\t\t\t\tvLogger(\"Doing auth with:username:%s:password:%s:\", up[0], up[1])\n\t\t\t\treq.SetBasicAuth(up[0], up[1])\n\n\t\t\t}\n\n\t\t\tif args.verbose {\n\n\t\t\t\tdump, _ := httputil.DumpRequestOut(req, true)\n\t\t\t\tvLogger(\"%s\", dump)\n\n\t\t\t}\n\n\t\t\tres, err = client.Do(req)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\targs.resultChan <- getReply{rv: false, err: err}\n\t\t\t\t_, err = ioutil.ReadAll(res.Body)\n\t\t\t\tres.Body.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, err = ioutil.ReadAll(res.Body)\n\t\t\tres.Body.Close()\n\n\t\t}\n\n\t\tif args.verbose {\n\n\t\t\tfmt.Println(res.Status)\n\t\t\tfor k, v := range res.Header {\n\t\t\t\tfmt.Println(k+\":\", v)\n\t\t\t}\n\n\t\t}\n\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\targs.resultChan <- getReply{rv: false}\n\t\t}\n\n\t\targs.resultChan <- getReply{rv: true}\n\n\t}\n\n}\n\nfunc WorkerPool(n int) chan *getArgs {\n\trequests := make(chan *getArgs)\n\n\tfor i := 0; i < n; i++ {\n\t\tgo get(requests)\n\t}\n\n\treturn requests\n}\n\nfunc main() {\n\n\tstatus := \"OK\"\n\trv := 0\n\tname := \"Bulk HTTP Check\"\n\tbad := 0\n\ttotal := 0\n\n\t\/\/ this needs improvement. the number of spaces here has to equal the number of chars in the badHosts append line suffix\n\tbadHosts := []byte(\" \")\n\n\t\/\/verbose := flag.Bool(\"v\", false, \"verbose output\")\n\tverbose = flag.Bool(\"v\", false, \"verbose output\")\n\twarn := flag.Int(\"w\", 10, \"warning level - number of non-200s or percentage of non-200s (default is numeric not percentage)\")\n\tcrit := flag.Int(\"c\", 20, \"critical level - number of non-200s or percentage of non-200s (default is numeric not percentage)\")\n\ttimeout := flag.Int(\"t\", 2, \"timeout in seconds - don't wait. Do Head requests and don't wait.\")\n\tpct := flag.Bool(\"pct\", false, \"interpret warming and critical levels are percentages\")\n\tpath := flag.String(\"path\", \"\", \"optional path to append to the input lines including the leading slash - these will not be urlencoded. This is ignored is the urls option is given.\")\n\tfile := flag.String(\"file\", \"\", \"input data source: a filename or '-' for STDIN.\")\n\tport := flag.Int(\"port\", 80, \"optional port for the http request - ignored if urls is specified\")\n\turls := flag.Bool(\"urls\", false, \"Assume the input data is full urls - its normally a list of hostnames\")\n\tauth := flag.String(\"auth\", \"\", \"Do basic auth with this username:passwd - ignored if urls is specified - make this use .netrc instead\")\n\tcheckName := flag.String(\"name\", \"\", \"a name to be included in the check output to distinguish the check output\")\n\tsilence := flag.Bool(\"silence\", false, \"don't make a huge list of all failing checks\")\n\tworkers := flag.Int(\"workers\", 5, \"how many workers to do the requests\")\n\n\tflag.Usage = func() {\n\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, `\n\tRead hostnames from a file or STDIN and do a single nagios check over\n\tthem all. Just check for 200s. Warning and Critical are either\n\tpercentages of the total, or a regular numeric thresholds.\n\n\tThe output contains the hostname of any non-200 reporting hosts (see -silence).\n\n\tSkip input lines that are commented out with shell style comments\n\tlike \/^#\/.\n\n\tDo Head requests since we don't care about the content. Make this\n\toptional some day.\n\n\tThe -path is appended to the hostnames to make full URLs for the checks.\n\n\tIf the -urls option is specified, then the input is assumed a complete URL, like http:\/\/$hostname:$port\/$path.\n\n\tExamples:\n\n\t.\/someCommand | .\/check_http_bulk -w 1 -c 2 -path '\/api\/aliveness-test\/%%2F\/' -port 15672 -file - -auth zup:nuch \n\n\t.\/check_http_bulk -urls -file urls.txt\n\n`)\n\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.Parse()\n\n\tif len(flag.Args()) > 0 {\n\n\t\tflag.Usage()\n\t\tos.Exit(3)\n\n\t}\n\n\t\/\/ it urls is specified, the input is full urls to be used enmasse and to be url encoded\n\tif *urls {\n\t\t*path = \"\"\n\t}\n\n\tif *checkName != \"\" {\n\t\tname = *checkName\n\t}\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tfmt.Println(name+\" Unknown: \", err)\n\t\t\tos.Exit(3)\n\t\t}\n\t}()\n\n\tif file == nil || *file == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(3)\n\t}\n\n\tinputSource := os.Stdin\n\n\tif (*file)[0] != \"-\"[0] {\n\n\t\tvar err error\n\n\t\tinputSource, err = os.Open(*file)\n\n\t\tif err != nil {\n\n\t\t\tfmt.Printf(\"Couldn't open the specified input file:%s:error:%v:\\n\\n\", name, err)\n\t\t\tflag.Usage()\n\t\t\tos.Exit(3)\n\n\t\t}\n\n\t}\n\n\trequests := WorkerPool(*workers)\n\tscanner := bufio.NewScanner(inputSource)\n\n\t\/\/leave some room since we start sending to this before we read from it\n\trepliesChannel := make(chan chan getReply, 1)\n\tfor scanner.Scan() {\n\n\t\thostname := scanner.Text()\n\n\t\tif len(hostname) == 0 {\n\n\t\t\tvLogger(\"skipping blank:\\n\")\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif hostname[0] == \"#\"[0] {\n\n\t\t\tvLogger(\"skipping:%s:\\n\", hostname)\n\n\t\t\tcontinue\n\t\t}\n\n\t\ttotal++\n\n\t\tvLogger(\"working on:%s:\\n\", hostname)\n\n\t\tthisReplyChan := make(chan getReply)\n\n\t\t\/\/put the reply chan into the chan of reply chans\n\t\trepliesChannel <- thisReplyChan\n\t\trequest := &getArgs{hostname: hostname, port: *port, path: *path, auth: *auth, urls: *urls, verbose: *verbose, timeout: *timeout, resultChan: thisReplyChan}\n\n\t\t\/\/send the request off so the workers can go\n\t\trequests <- request\n\n\t\t\/\/get a replyChannel that's ready\n\t\treadyReplyChan := <-repliesChannel\n\n\t\t\/\/read a reply\n\t\tresult := <-readyReplyChan\n\n\t\terr := result.err\n\t\tgoodCheck := result.rv\n\n\t\tif err != nil {\n\n\t\t\tfmt.Printf(\"%s get error: %T %s %#v\\n\", name, err, err, err)\n\t\t\tif !*silence {\n\t\t\t\tbadHosts = append(badHosts, hostname...)\n\t\t\t\tbadHosts = append(badHosts, \", \"...)\n\t\t\t}\n\t\t\tbad++\n\n\t\t\tcontinue\n\n\t\t}\n\n\t\tif !goodCheck {\n\t\t\tif !*silence {\n\t\t\t\tbadHosts = append(badHosts, hostname...)\n\t\t\t\tbadHosts = append(badHosts, \", \"...)\n\t\t\t}\n\t\t\tbad++\n\t\t}\n\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n\t\tstatus = \"Unknown\"\n\t\trv = 3\n\t}\n\n\tif *pct {\n\n\t\tratio := int(float64(bad) \/ float64(total) * 100)\n\n\t\tvLogger(\"ratio:%d:\\n\", ratio)\n\n\t\tif ratio >= *crit {\n\t\t\tstatus = \"Critical\"\n\t\t\trv = 2\n\t\t} else if ratio >= *warn {\n\t\t\tstatus = \"Warning\"\n\t\t\trv = 1\n\t\t}\n\n\t} else {\n\n\t\tif bad >= *crit {\n\t\t\tstatus = \"Critical\"\n\t\t\trv = 2\n\t\t} else if bad >= *warn {\n\t\t\tstatus = \"Warning\"\n\t\t\trv = 1\n\t\t}\n\n\t}\n\n\tfmt.Printf(\"%s %s: %d of %d failed|%s\\n\", name, status, bad, total, badHosts[:len(badHosts)-2])\n\tos.Exit(rv)\n}\nfix the concurrencypackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar verbose *bool\n\ntype getArgs struct {\n\thostname string\n\tport int\n\tpath string\n\tauth string\n\turls bool\n\tverbose bool\n\ttimeout int\n\tresultChan chan getReply\n}\n\ntype getReply struct {\n\terr interface{}\n\trv bool\n}\n\nfunc vLogger(msg string, args ...interface{}) {\n\n\tif *verbose {\n\t\tfmt.Fprintf(os.Stderr, msg, args...)\n\t}\n\n}\n\nfunc get(request chan *getArgs) {\n\n\tvar err error\n\n\tfor args := range request {\n\n\t\tvLogger(\"fetching:hostname:%s:\\n\", args.hostname)\n\n\t\tres := &http.Response{}\n\n\t\tif args.urls {\n\n\t\t\turl := args.hostname\n\t\t\tres, err = http.Head(url)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\targs.resultChan <- getReply{rv: false, err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, err = ioutil.ReadAll(res.Body)\n\t\t\tres.Body.Close()\n\n\t\t} else {\n\n\t\t\tclient := &http.Client{Timeout: time.Duration(args.timeout) * time.Second}\n\n\t\t\t\/\/ had to allocate this or the SetBasicAuth will panic\n\t\t\theaders := make(map[string][]string)\n\t\t\thostPort := fmt.Sprintf(\"%s:%d\", args.hostname, args.port)\n\n\t\t\tvLogger(\"adding hostPort:%s:%d:path:%s:\\n\", args.hostname, args.port, args.path)\n\n\t\t\treq := &http.Request{\n\t\t\t\tMethod: \"HEAD\",\n\t\t\t\t\/\/ Host: hostPort,\n\t\t\t\tURL: &url.URL{\n\t\t\t\t\tHost: hostPort,\n\t\t\t\t\tScheme: \"http\",\n\t\t\t\t\tOpaque: args.path,\n\t\t\t\t},\n\t\t\t\tHeader: headers,\n\t\t\t}\n\n\t\t\tif args.auth != \"\" {\n\n\t\t\t\tup := strings.SplitN(args.auth, \":\", 2)\n\n\t\t\t\tvLogger(\"Doing auth with:username:%s:password:%s:\", up[0], up[1])\n\t\t\t\treq.SetBasicAuth(up[0], up[1])\n\n\t\t\t}\n\n\t\t\tif args.verbose {\n\n\t\t\t\tdump, _ := httputil.DumpRequestOut(req, true)\n\t\t\t\tvLogger(\"%s\", dump)\n\n\t\t\t}\n\n\t\t\tres, err = client.Do(req)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\targs.resultChan <- getReply{rv: false, err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, err = ioutil.ReadAll(res.Body)\n\t\t\tres.Body.Close()\n\n\t\t}\n\n\t\tif args.verbose {\n\n\t\t\tfmt.Println(res.Status)\n\t\t\tfor k, v := range res.Header {\n\t\t\t\tfmt.Println(k+\":\", v)\n\t\t\t}\n\n\t\t}\n\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\targs.resultChan <- getReply{rv: false}\n\t\t}\n\n\t\targs.resultChan <- getReply{rv: true}\n\n\t}\n\n}\n\nfunc WorkerPool(n int) chan *getArgs {\n\trequests := make(chan *getArgs)\n\n\tfor i := 0; i < n; i++ {\n\t\tgo get(requests)\n\t}\n\n\treturn requests\n}\n\nfunc main() {\n\n\tstatus := \"OK\"\n\trv := 0\n\tname := \"Bulk HTTP Check\"\n\tbad := 0\n\ttotal := 0\n\n\t\/\/ this needs improvement. the number of spaces here has to equal the number of chars in the badHosts append line suffix\n\tbadHosts := []byte(\" \")\n\n\t\/\/verbose := flag.Bool(\"v\", false, \"verbose output\")\n\tverbose = flag.Bool(\"v\", false, \"verbose output\")\n\twarn := flag.Int(\"w\", 10, \"warning level - number of non-200s or percentage of non-200s (default is numeric not percentage)\")\n\tcrit := flag.Int(\"c\", 20, \"critical level - number of non-200s or percentage of non-200s (default is numeric not percentage)\")\n\ttimeout := flag.Int(\"t\", 2, \"timeout in seconds - don't wait. Do Head requests and don't wait.\")\n\tpct := flag.Bool(\"pct\", false, \"interpret warming and critical levels are percentages\")\n\tpath := flag.String(\"path\", \"\", \"optional path to append to the input lines including the leading slash - these will not be urlencoded. This is ignored is the urls option is given.\")\n\tfile := flag.String(\"file\", \"\", \"input data source: a filename or '-' for STDIN.\")\n\tport := flag.Int(\"port\", 80, \"optional port for the http request - ignored if urls is specified\")\n\turls := flag.Bool(\"urls\", false, \"Assume the input data is full urls - its normally a list of hostnames\")\n\tauth := flag.String(\"auth\", \"\", \"Do basic auth with this username:passwd - ignored if urls is specified - make this use .netrc instead\")\n\tcheckName := flag.String(\"name\", \"\", \"a name to be included in the check output to distinguish the check output\")\n\tsilence := flag.Bool(\"silence\", false, \"don't make a huge list of all failing checks\")\n\tworkers := flag.Int(\"workers\", 5, \"how many workers to do the requests\")\n\n\tflag.Usage = func() {\n\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, `\n\tRead hostnames from a file or STDIN and do a single nagios check over\n\tthem all. Just check for 200s. Warning and Critical are either\n\tpercentages of the total, or a regular numeric thresholds.\n\n\tThe output contains the hostname of any non-200 reporting hosts (see -silence).\n\n\tSkip input lines that are commented out with shell style comments\n\tlike \/^#\/.\n\n\tDo Head requests since we don't care about the content. Make this\n\toptional some day.\n\n\tThe -path is appended to the hostnames to make full URLs for the checks.\n\n\tIf the -urls option is specified, then the input is assumed a complete URL, like http:\/\/$hostname:$port\/$path.\n\n\tExamples:\n\n\t.\/someCommand | .\/check_http_bulk -w 1 -c 2 -path '\/api\/aliveness-test\/%%2F\/' -port 15672 -file - -auth zup:nuch \n\n\t.\/check_http_bulk -urls -file urls.txt\n\n`)\n\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.Parse()\n\n\tif len(flag.Args()) > 0 {\n\n\t\tflag.Usage()\n\t\tos.Exit(3)\n\n\t}\n\n\t\/\/ it urls is specified, the input is full urls to be used enmasse and to be url encoded\n\tif *urls {\n\t\t*path = \"\"\n\t}\n\n\tif *checkName != \"\" {\n\t\tname = *checkName\n\t}\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tfmt.Println(name+\" Unknown: \", err)\n\t\t\tos.Exit(3)\n\t\t}\n\t}()\n\n\tif file == nil || *file == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(3)\n\t}\n\n\tinputSource := os.Stdin\n\n\tif (*file)[0] != \"-\"[0] {\n\n\t\tvar err error\n\n\t\tinputSource, err = os.Open(*file)\n\n\t\tif err != nil {\n\n\t\t\tfmt.Printf(\"Couldn't open the specified input file:%s:error:%v:\\n\\n\", name, err)\n\t\t\tflag.Usage()\n\t\t\tos.Exit(3)\n\n\t\t}\n\n\t}\n\n\trequests := WorkerPool(*workers)\n\tscanner := bufio.NewScanner(inputSource)\n\n\t\/\/leave some room since we start sending to this before we read from it\n\trepliesChannel := make(chan getReply, 1)\n\tfor scanner.Scan() {\n\n\t\thostname := scanner.Text()\n\n\t\tif len(hostname) == 0 {\n\n\t\t\tvLogger(\"skipping blank:\\n\")\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif hostname[0] == \"#\"[0] {\n\n\t\t\tvLogger(\"skipping:%s:\\n\", hostname)\n\n\t\t\tcontinue\n\t\t}\n\n\t\ttotal++\n\n\t\tvLogger(\"working on:%s:\\n\", hostname)\n\n\t\trequest := &getArgs{hostname: hostname, port: *port, path: *path, auth: *auth, urls: *urls, verbose: *verbose, timeout: *timeout, resultChan: repliesChannel}\n\n\t\t\/\/send the request off so the workers can go\n\t\trequests <- request\n\n\t\t\/\/read a reply\n\t\tselect {\n\n\t\tcase\tresult := <-repliesChannel:\n\n\t\t\terr := result.err\n\t\t\tgoodCheck := result.rv\n\n\t\t\tif err != nil {\n\n\t\t\t\tfmt.Printf(\"%s get error: %T %s %#v\\n\", name, err, err, err)\n\t\t\t\tif !*silence {\n\t\t\t\t\tbadHosts = append(badHosts, hostname...)\n\t\t\t\t\tbadHosts = append(badHosts, \", \"...)\n\t\t\t\t}\n\t\t\t\tbad++\n\n\t\t\t\tcontinue\n\n\t\t\t}\n\n\t\t\tif !goodCheck {\n\t\t\t\tif !*silence {\n\t\t\t\t\tbadHosts = append(badHosts, hostname...)\n\t\t\t\t\tbadHosts = append(badHosts, \", \"...)\n\t\t\t\t}\n\t\t\t\tbad++\n\t\t\t}\n\n\t\tdefault:\n\n\t\t}\n\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n\t\tstatus = \"Unknown\"\n\t\trv = 3\n\t}\n\n\tif *pct {\n\n\t\tratio := int(float64(bad) \/ float64(total) * 100)\n\n\t\tvLogger(\"ratio:%d:\\n\", ratio)\n\n\t\tif ratio >= *crit {\n\t\t\tstatus = \"Critical\"\n\t\t\trv = 2\n\t\t} else if ratio >= *warn {\n\t\t\tstatus = \"Warning\"\n\t\t\trv = 1\n\t\t}\n\n\t} else {\n\n\t\tif bad >= *crit {\n\t\t\tstatus = \"Critical\"\n\t\t\trv = 2\n\t\t} else if bad >= *warn {\n\t\t\tstatus = \"Warning\"\n\t\t\trv = 1\n\t\t}\n\n\t}\n\n\tfmt.Printf(\"%s %s: %d of %d failed|%s\\n\", name, status, bad, total, badHosts[:len(badHosts)-2])\n\tos.Exit(rv)\n}\n<|endoftext|>"} {"text":"package cmd\n\nimport (\n\t\"log\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar cmdRecordsDelete = cli.Command{\n\tName: \"delete\",\n\tUsage: \"deletes zone record\",\n\tArgsUsage: \" [ ...]\",\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName: \"all\",\n\t\t\tUsage: \"deletes all zone records\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"type\",\n\t\t\tUsage: \"deletes only records of given type (can be comma separated)\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"ignore\",\n\t\t\tUsage: \"ignores records of given type (can be comma separated)\",\n\t\t},\n\t},\n\tAction: func(c *cli.Context) {\n\t\tzoneID, err := getZoneID(c)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !c.Bool(\"all\") {\n\t\t\tif len(c.Args()) < 1 {\n\t\t\t\tlog.Fatal(\"Usage error: --all flag or at least one record id is required.\")\n\t\t\t} else if c.String(\"type\") != \"\" {\n\t\t\t\tlog.Fatal(\"Usage error: --type can be only used with --all.\")\n\t\t\t} else if c.String(\"ignore\") != \"\" {\n\t\t\t\tlog.Fatal(\"Usage error: --type can be only used with --all.\")\n\t\t\t}\n\t\t}\n\n\t\tvar (\n\t\t\tids []string\n\t\t\ttypes = splitComma(c.String(\"type\"))\n\t\t\tignore = splitComma(c.String(\"ignore\"))\n\t\t)\n\n\t\tif c.Bool(\"all\") {\n\t\t\trecords, err := client(c).Records.List(context.Background(), zoneID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error listing records: %v\", err)\n\t\t\t}\n\t\t\tfor _, record := range records {\n\t\t\t\tif stringIn(record.Type, ignore) {\n\t\t\t\t\tlog.Printf(\"Ignoring record %s (type=%s)\", record.ID, record.Type)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(types) > 0 && !stringIn(record.Type, types) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tids = append(ids, record.ID)\n\t\t\t}\n\t\t} else {\n\t\t\tids = c.Args()\n\t\t}\n\n\t\tfor _, id := range ids {\n\t\t\terr := client(c).Records.Delete(context.Background(), zoneID, id)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error deleting %q: %v\", id, err)\n\t\t\t}\n\t\t\tlog.Printf(\"Deleted record with id %q.\", id)\n\t\t}\n\t},\n}\nFix cli usage error messagepackage cmd\n\nimport (\n\t\"log\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar cmdRecordsDelete = cli.Command{\n\tName: \"delete\",\n\tUsage: \"deletes zone record\",\n\tArgsUsage: \" [ ...]\",\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName: \"all\",\n\t\t\tUsage: \"deletes all zone records\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"type\",\n\t\t\tUsage: \"deletes only records of given type (can be comma separated)\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"ignore\",\n\t\t\tUsage: \"ignores records of given type (can be comma separated)\",\n\t\t},\n\t},\n\tAction: func(c *cli.Context) {\n\t\tzoneID, err := getZoneID(c)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !c.Bool(\"all\") {\n\t\t\tif len(c.Args()) < 1 {\n\t\t\t\tlog.Fatal(\"Usage error: --all flag or at least one record id is required.\")\n\t\t\t} else if c.String(\"type\") != \"\" {\n\t\t\t\tlog.Fatal(\"Usage error: --type can be only used with --all.\")\n\t\t\t} else if c.String(\"ignore\") != \"\" {\n\t\t\t\tlog.Fatal(\"Usage error: --ignore can be only used with --all.\")\n\t\t\t}\n\t\t}\n\n\t\tvar (\n\t\t\tids []string\n\t\t\ttypes = splitComma(c.String(\"type\"))\n\t\t\tignore = splitComma(c.String(\"ignore\"))\n\t\t)\n\n\t\tif c.Bool(\"all\") {\n\t\t\trecords, err := client(c).Records.List(context.Background(), zoneID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error listing records: %v\", err)\n\t\t\t}\n\t\t\tfor _, record := range records {\n\t\t\t\tif stringIn(record.Type, ignore) {\n\t\t\t\t\tlog.Printf(\"Ignoring record %s (type=%s)\", record.ID, record.Type)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(types) > 0 && !stringIn(record.Type, types) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tids = append(ids, record.ID)\n\t\t\t}\n\t\t} else {\n\t\t\tids = c.Args()\n\t\t}\n\n\t\tfor _, id := range ids {\n\t\t\terr := client(c).Records.Delete(context.Background(), zoneID, id)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error deleting %q: %v\", id, err)\n\t\t\t}\n\t\t\tlog.Printf(\"Deleted record with id %q.\", id)\n\t\t}\n\t},\n}\n<|endoftext|>"} {"text":"package buffer\n\nimport (\n\t\"crypto\/rand\"\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"testing\"\n\t\"unsafe\"\n)\n\nfunc toByteSlice(p unsafe.Pointer, n int) []byte {\n\tsh := reflect.SliceHeader{\n\t\tData: uintptr(p),\n\t\tLen: n,\n\t\tCap: n,\n\t}\n\n\treturn *(*[]byte)(unsafe.Pointer(&sh))\n}\n\n\/\/ fillWithGarbage writes random data to [p, p+n).\nfunc fillWithGarbage(p unsafe.Pointer, n int) (err error) {\n\tb := toByteSlice(p, n)\n\t_, err = io.ReadFull(rand.Reader, b)\n\treturn\n}\n\nfunc randBytes(n int) (b []byte, err error) {\n\tb = make([]byte, n)\n\t_, err = io.ReadFull(rand.Reader, b)\n\treturn\n}\n\n\/\/ findNonZero finds the offset of the first non-zero byte in [p, p+n). If\n\/\/ none, it returns n.\nfunc findNonZero(p unsafe.Pointer, n int) int {\n\tb := toByteSlice(p, n)\n\tfor i, x := range b {\n\t\tif x != 0 {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn n\n}\n\nfunc TestMemclr(t *testing.T) {\n\t\/\/ All sizes up to 32 bytes.\n\tvar sizes []int\n\tfor i := 0; i <= 32; i++ {\n\t\tsizes = append(sizes, i)\n\t}\n\n\t\/\/ And a few hand-chosen sizes.\n\tsizes = append(sizes, []int{\n\t\t39, 41, 64, 127, 128, 129,\n\t\t1<<20 - 1,\n\t\t1 << 20,\n\t\t1<<20 + 1,\n\t}...)\n\n\t\/\/ For each size, fill a buffer with random bytes and then zero it.\n\tfor _, size := range sizes {\n\t\tsize := size\n\t\tt.Run(fmt.Sprintf(\"size=%d\", size), func(t *testing.T) {\n\t\t\t\/\/ Generate\n\t\t\tb, err := randBytes(size)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"randBytes: %v\", err)\n\t\t\t}\n\n\t\t\t\/\/ Clear\n\t\t\tvar p unsafe.Pointer\n\t\t\tif len(b) != 0 {\n\t\t\t\tp = unsafe.Pointer(&b[0])\n\t\t\t}\n\n\t\t\tmemclr(p, uintptr(len(b)))\n\n\t\t\t\/\/ Check\n\t\t\tif i := findNonZero(p, len(b)); i != len(b) {\n\t\t\t\tt.Fatalf(\"non-zero byte at offset %d\", i)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestOutMessageAppend(t *testing.T) {\n\tt.Fatal(\"TODO\")\n}\n\nfunc TestOutMessageAppendString(t *testing.T) {\n\tt.Fatal(\"TODO\")\n}\n\nfunc TestOutMessageShrinkTo(t *testing.T) {\n\tt.Fatal(\"TODO\")\n}\n\nfunc TestOutMessageHeader(t *testing.T) {\n\tt.Fatal(\"TODO\")\n}\n\nfunc TestOutMessageReset(t *testing.T) {\n\tvar om OutMessage\n\th := om.OutHeader()\n\n\tconst trials = 10\n\tfor i := 0; i < trials; i++ {\n\t\t\/\/ Fill the header with garbage.\n\t\terr := fillWithGarbage(unsafe.Pointer(h), int(unsafe.Sizeof(*h)))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"fillWithGarbage: %v\", err)\n\t\t}\n\n\t\t\/\/ Ensure a non-zero payload length.\n\t\tif p := om.GrowNoZero(128); p == nil {\n\t\t\tt.Fatal(\"GrowNoZero failed\")\n\t\t}\n\n\t\t\/\/ Reset.\n\t\tom.Reset()\n\n\t\t\/\/ Check that the length was updated.\n\t\tif got, want := int(om.Len()), int(OutMessageInitialSize); got != want {\n\t\t\tt.Fatalf(\"om.Len() = %d, want %d\", got, want)\n\t\t}\n\n\t\t\/\/ Check that the header was zeroed.\n\t\tif h.Len != 0 {\n\t\t\tt.Fatalf(\"non-zero Len %v\", h.Len)\n\t\t}\n\n\t\tif h.Error != 0 {\n\t\t\tt.Fatalf(\"non-zero Error %v\", h.Error)\n\t\t}\n\n\t\tif h.Unique != 0 {\n\t\t\tt.Fatalf(\"non-zero Unique %v\", h.Unique)\n\t\t}\n\t}\n}\n\nfunc TestOutMessageGrow(t *testing.T) {\n\tvar om OutMessage\n\n\t\/\/ Overwrite with garbage.\n\terr := fillWithGarbage(unsafe.Pointer(&om), int(unsafe.Sizeof(om)))\n\tif err != nil {\n\t\tt.Fatalf(\"fillWithGarbage: %v\", err)\n\t}\n\n\t\/\/ Zero the header.\n\tom.Reset()\n\n\t\/\/ Grow to the max size. This should zero the message.\n\tif p := om.Grow(MaxReadSize); p == nil {\n\t\tt.Fatal(\"Grow returned nil\")\n\t}\n\n\t\/\/ Check that everything has been zeroed.\n\tb := om.Bytes()\n\tfor i, x := range b {\n\t\tif x != 0 {\n\t\t\tt.Fatalf(\"non-zero byte 0x%02x at offset %d\", x, i)\n\t\t}\n\t}\n}\n\nfunc BenchmarkOutMessageReset(b *testing.B) {\n\t\/\/ A single buffer, which should fit in some level of CPU cache.\n\tb.Run(\"Single buffer\", func(b *testing.B) {\n\t\tvar om OutMessage\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tom.Reset()\n\t\t}\n\n\t\tb.SetBytes(int64(om.offset))\n\t})\n\n\t\/\/ Many megabytes worth of buffers, which should defeat the CPU cache.\n\tb.Run(\"Many buffers\", func(b *testing.B) {\n\t\t\/\/ The number of messages; intentionally a power of two.\n\t\tconst numMessages = 128\n\n\t\tvar oms [numMessages]OutMessage\n\t\tif s := unsafe.Sizeof(oms); s < 128<<20 {\n\t\t\tpanic(fmt.Sprintf(\"Array is too small; total size: %d\", s))\n\t\t}\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toms[i%numMessages].Reset()\n\t\t}\n\n\t\tb.SetBytes(int64(oms[0].offset))\n\t})\n}\n\nfunc BenchmarkOutMessageGrowShrink(b *testing.B) {\n\t\/\/ A single buffer, which should fit in some level of CPU cache.\n\tb.Run(\"Single buffer\", func(b *testing.B) {\n\t\tvar om OutMessage\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tom.Grow(MaxReadSize)\n\t\t\tom.ShrinkTo(OutMessageInitialSize)\n\t\t}\n\n\t\tb.SetBytes(int64(MaxReadSize))\n\t})\n\n\t\/\/ Many megabytes worth of buffers, which should defeat the CPU cache.\n\tb.Run(\"Many buffers\", func(b *testing.B) {\n\t\t\/\/ The number of messages; intentionally a power of two.\n\t\tconst numMessages = 128\n\n\t\tvar oms [numMessages]OutMessage\n\t\tif s := unsafe.Sizeof(oms); s < 128<<20 {\n\t\t\tpanic(fmt.Sprintf(\"Array is too small; total size: %d\", s))\n\t\t}\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toms[i%numMessages].Grow(MaxReadSize)\n\t\t\toms[i%numMessages].ShrinkTo(OutMessageInitialSize)\n\t\t}\n\n\t\tb.SetBytes(int64(MaxReadSize))\n\t})\n}\nbuffer_test: expand the coverage of TestOutMessageGrow.package buffer\n\nimport (\n\t\"crypto\/rand\"\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"testing\"\n\t\"unsafe\"\n)\n\nfunc toByteSlice(p unsafe.Pointer, n int) []byte {\n\tsh := reflect.SliceHeader{\n\t\tData: uintptr(p),\n\t\tLen: n,\n\t\tCap: n,\n\t}\n\n\treturn *(*[]byte)(unsafe.Pointer(&sh))\n}\n\n\/\/ fillWithGarbage writes random data to [p, p+n).\nfunc fillWithGarbage(p unsafe.Pointer, n int) (err error) {\n\tb := toByteSlice(p, n)\n\t_, err = io.ReadFull(rand.Reader, b)\n\treturn\n}\n\nfunc randBytes(n int) (b []byte, err error) {\n\tb = make([]byte, n)\n\t_, err = io.ReadFull(rand.Reader, b)\n\treturn\n}\n\n\/\/ findNonZero finds the offset of the first non-zero byte in [p, p+n). If\n\/\/ none, it returns n.\nfunc findNonZero(p unsafe.Pointer, n int) int {\n\tb := toByteSlice(p, n)\n\tfor i, x := range b {\n\t\tif x != 0 {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn n\n}\n\nfunc TestMemclr(t *testing.T) {\n\t\/\/ All sizes up to 32 bytes.\n\tvar sizes []int\n\tfor i := 0; i <= 32; i++ {\n\t\tsizes = append(sizes, i)\n\t}\n\n\t\/\/ And a few hand-chosen sizes.\n\tsizes = append(sizes, []int{\n\t\t39, 41, 64, 127, 128, 129,\n\t\t1<<20 - 1,\n\t\t1 << 20,\n\t\t1<<20 + 1,\n\t}...)\n\n\t\/\/ For each size, fill a buffer with random bytes and then zero it.\n\tfor _, size := range sizes {\n\t\tsize := size\n\t\tt.Run(fmt.Sprintf(\"size=%d\", size), func(t *testing.T) {\n\t\t\t\/\/ Generate\n\t\t\tb, err := randBytes(size)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"randBytes: %v\", err)\n\t\t\t}\n\n\t\t\t\/\/ Clear\n\t\t\tvar p unsafe.Pointer\n\t\t\tif len(b) != 0 {\n\t\t\t\tp = unsafe.Pointer(&b[0])\n\t\t\t}\n\n\t\t\tmemclr(p, uintptr(len(b)))\n\n\t\t\t\/\/ Check\n\t\t\tif i := findNonZero(p, len(b)); i != len(b) {\n\t\t\t\tt.Fatalf(\"non-zero byte at offset %d\", i)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestOutMessageAppend(t *testing.T) {\n\tt.Fatal(\"TODO\")\n}\n\nfunc TestOutMessageAppendString(t *testing.T) {\n\tt.Fatal(\"TODO\")\n}\n\nfunc TestOutMessageShrinkTo(t *testing.T) {\n\tt.Fatal(\"TODO\")\n}\n\nfunc TestOutMessageHeader(t *testing.T) {\n\tt.Fatal(\"TODO\")\n}\n\nfunc TestOutMessageReset(t *testing.T) {\n\tvar om OutMessage\n\th := om.OutHeader()\n\n\tconst trials = 10\n\tfor i := 0; i < trials; i++ {\n\t\t\/\/ Fill the header with garbage.\n\t\terr := fillWithGarbage(unsafe.Pointer(h), int(unsafe.Sizeof(*h)))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"fillWithGarbage: %v\", err)\n\t\t}\n\n\t\t\/\/ Ensure a non-zero payload length.\n\t\tif p := om.GrowNoZero(128); p == nil {\n\t\t\tt.Fatal(\"GrowNoZero failed\")\n\t\t}\n\n\t\t\/\/ Reset.\n\t\tom.Reset()\n\n\t\t\/\/ Check that the length was updated.\n\t\tif got, want := int(om.Len()), int(OutMessageInitialSize); got != want {\n\t\t\tt.Fatalf(\"om.Len() = %d, want %d\", got, want)\n\t\t}\n\n\t\t\/\/ Check that the header was zeroed.\n\t\tif h.Len != 0 {\n\t\t\tt.Fatalf(\"non-zero Len %v\", h.Len)\n\t\t}\n\n\t\tif h.Error != 0 {\n\t\t\tt.Fatalf(\"non-zero Error %v\", h.Error)\n\t\t}\n\n\t\tif h.Unique != 0 {\n\t\t\tt.Fatalf(\"non-zero Unique %v\", h.Unique)\n\t\t}\n\t}\n}\n\nfunc TestOutMessageGrow(t *testing.T) {\n\tvar om OutMessage\n\tom.Reset()\n\n\t\/\/ Set up garbage where the payload will soon be.\n\tconst payloadSize = 1234\n\t{\n\t\tp := om.GrowNoZero(payloadSize)\n\t\tif p == nil {\n\t\t\tt.Fatal(\"GrowNoZero failed\")\n\t\t}\n\n\t\terr := fillWithGarbage(p, payloadSize)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"fillWithGarbage: %v\", err)\n\t\t}\n\n\t\tom.ShrinkTo(OutMessageInitialSize)\n\t}\n\n\t\/\/ Call Grow.\n\tif p := om.Grow(payloadSize); p == nil {\n\t\tt.Fatal(\"Grow failed\")\n\t}\n\n\t\/\/ Check the resulting length in two ways.\n\tconst wantLen = int(payloadSize + OutMessageInitialSize)\n\tif got, want := om.Len(), wantLen; got != want {\n\t\tt.Errorf(\"om.Len() = %d, want %d\", got)\n\t}\n\n\tb := om.Bytes()\n\tif got, want := len(b), wantLen; got != want {\n\t\tt.Fatalf(\"len(om.Len()) = %d, want %d\", got)\n\t}\n\n\t\/\/ Check that the payload was zeroed.\n\tfor i, x := range b[OutMessageInitialSize:] {\n\t\tif x != 0 {\n\t\t\tt.Fatalf(\"non-zero byte 0x%02x at payload offset %d\", x, i)\n\t\t}\n\t}\n}\n\nfunc BenchmarkOutMessageReset(b *testing.B) {\n\t\/\/ A single buffer, which should fit in some level of CPU cache.\n\tb.Run(\"Single buffer\", func(b *testing.B) {\n\t\tvar om OutMessage\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tom.Reset()\n\t\t}\n\n\t\tb.SetBytes(int64(om.offset))\n\t})\n\n\t\/\/ Many megabytes worth of buffers, which should defeat the CPU cache.\n\tb.Run(\"Many buffers\", func(b *testing.B) {\n\t\t\/\/ The number of messages; intentionally a power of two.\n\t\tconst numMessages = 128\n\n\t\tvar oms [numMessages]OutMessage\n\t\tif s := unsafe.Sizeof(oms); s < 128<<20 {\n\t\t\tpanic(fmt.Sprintf(\"Array is too small; total size: %d\", s))\n\t\t}\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toms[i%numMessages].Reset()\n\t\t}\n\n\t\tb.SetBytes(int64(oms[0].offset))\n\t})\n}\n\nfunc BenchmarkOutMessageGrowShrink(b *testing.B) {\n\t\/\/ A single buffer, which should fit in some level of CPU cache.\n\tb.Run(\"Single buffer\", func(b *testing.B) {\n\t\tvar om OutMessage\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tom.Grow(MaxReadSize)\n\t\t\tom.ShrinkTo(OutMessageInitialSize)\n\t\t}\n\n\t\tb.SetBytes(int64(MaxReadSize))\n\t})\n\n\t\/\/ Many megabytes worth of buffers, which should defeat the CPU cache.\n\tb.Run(\"Many buffers\", func(b *testing.B) {\n\t\t\/\/ The number of messages; intentionally a power of two.\n\t\tconst numMessages = 128\n\n\t\tvar oms [numMessages]OutMessage\n\t\tif s := unsafe.Sizeof(oms); s < 128<<20 {\n\t\t\tpanic(fmt.Sprintf(\"Array is too small; total size: %d\", s))\n\t\t}\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\toms[i%numMessages].Grow(MaxReadSize)\n\t\t\toms[i%numMessages].ShrinkTo(OutMessageInitialSize)\n\t\t}\n\n\t\tb.SetBytes(int64(MaxReadSize))\n\t})\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"log\"\n\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/v2\/rest\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n)\n\nfunc main() {\n\tc := rest.NewClient()\n\n\tpulseHist, err := c.Pulse.PublicPulseHistory(\"\", \"\")\n\tif err != nil {\n\t\tlog.Fatalf(\"PublicPulseHistory: %s\", err)\n\t}\n\n\tspew.Dump(pulseHist)\n}\npublic hist example fixpackage main\n\nimport (\n\t\"log\"\n\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/v2\/rest\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n)\n\nfunc main() {\n\tc := rest.NewClient()\n\n\tpulseHist, err := c.Pulse.PublicPulseHistory(0, 0)\n\tif err != nil {\n\t\tlog.Fatalf(\"PublicPulseHistory: %s\", err)\n\t}\n\n\tspew.Dump(pulseHist)\n}\n<|endoftext|>"} {"text":"package shell_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"gitlab.com\/gitlab-org\/gitlab-ci-multi-runner\/common\"\n\t\"gitlab.com\/gitlab-org\/gitlab-ci-multi-runner\/helpers\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc TestBashShellSuccessRun(t *testing.T) {\n\tif helpers.SkipIntegrationTests(t, \"bash\") {\n\t\treturn\n\t}\n\n\tbuild := &common.Build{\n\t\tGetBuildResponse: common.SuccessfulBuild,\n\t\tRunner: &common.RunnerConfig{\n\t\t\tRunnerSettings: common.RunnerSettings{\n\t\t\t\tExecutor: \"shell\",\n\t\t\t\tShell: \"bash\",\n\t\t\t},\n\t\t},\n\t}\n\n\terr := build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout})\n\tassert.NoError(t, err)\n}\n\nfunc TestWindowsBatchSuccessRun(t *testing.T) {\n\tif helpers.SkipIntegrationTests(t, \"cmd.exe\") {\n\t\treturn\n\t}\n\n\tbuild := &common.Build{\n\t\tGetBuildResponse: common.SuccessfulBuild,\n\t\tRunner: &common.RunnerConfig{\n\t\t\tRunnerSettings: common.RunnerSettings{\n\t\t\t\tExecutor: \"shell\",\n\t\t\t\tShell: \"cmd\",\n\t\t\t},\n\t\t},\n\t}\n\n\terr := build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout})\n\tassert.NoError(t, err)\n}\n\nfunc TestPowerShellSuccessRun(t *testing.T) {\n\tif helpers.SkipIntegrationTests(t, \"powershell.exe\") {\n\t\treturn\n\t}\n\n\tbuild := &common.Build{\n\t\tGetBuildResponse: common.SuccessfulBuild,\n\t\tRunner: &common.RunnerConfig{\n\t\t\tRunnerSettings: common.RunnerSettings{\n\t\t\t\tExecutor: \"shell\",\n\t\t\t\tShell: \"powershell\",\n\t\t\t},\n\t\t},\n\t}\n\n\terr := build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout})\n\tassert.NoError(t, err)\n}\n\nfunc TestShellBuildAbort(t *testing.T) {\n\tif helpers.SkipIntegrationTests(t) {\n\t\treturn\n\t}\n\n\tbuild := &common.Build{\n\t\tGetBuildResponse: common.LongRunningBuild,\n\t\tRunner: &common.RunnerConfig{\n\t\t\tRunnerSettings: common.RunnerSettings{\n\t\t\t\tExecutor: \"shell\",\n\t\t\t},\n\t\t},\n\t\tSystemInterrupt: make(chan os.Signal, 1),\n\t}\n\n\tabortTimer := time.AfterFunc(time.Second, func() {\n\t\tt.Log(\"Interrupt\")\n\t\tbuild.SystemInterrupt <- os.Interrupt\n\t})\n\tdefer abortTimer.Stop()\n\n\ttimeoutTimer := time.AfterFunc(time.Second*3, func() {\n\t\tt.Log(\"Timedout\")\n\t\tt.FailNow()\n\t})\n\tdefer timeoutTimer.Stop()\n\n\terr := build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout})\n\tassert.EqualError(t, err, \"aborted: interrupt\")\n}\n\nfunc TestShellBuildCancel(t *testing.T) {\n\tif helpers.SkipIntegrationTests(t) {\n\t\treturn\n\t}\n\n\tbuild := &common.Build{\n\t\tGetBuildResponse: common.LongRunningBuild,\n\t\tRunner: &common.RunnerConfig{\n\t\t\tRunnerSettings: common.RunnerSettings{\n\t\t\t\tExecutor: \"shell\",\n\t\t\t},\n\t\t},\n\t}\n\n\ttrace := &common.Trace{Writer: os.Stdout, Abort: make(chan interface{}, 1)}\n\n\tabortTimer := time.AfterFunc(time.Second, func() {\n\t\tt.Log(\"Interrupt\")\n\t\ttrace.Abort <- true\n\t})\n\tdefer abortTimer.Stop()\n\n\ttimeoutTimer := time.AfterFunc(time.Second*3, func() {\n\t\tt.Log(\"Timedout\")\n\t\tt.FailNow()\n\t})\n\tdefer timeoutTimer.Stop()\n\n\terr := build.Run(&common.Config{}, trace)\n\tassert.EqualError(t, err, \"canceled\")\n\tassert.IsType(t, err, &common.BuildError{})\n}\n\nfunc runBuildWithIndexLockForShell(t *testing.T, shell string) {\n\tif helpers.SkipIntegrationTests(t, shell) {\n\t\treturn\n\t}\n\n\tbuild := &common.Build{\n\t\tGetBuildResponse: common.SuccessfulBuild,\n\t\tRunner: &common.RunnerConfig{\n\t\t\tRunnerSettings: common.RunnerSettings{\n\t\t\t\tExecutor: \"shell\",\n\t\t\t\tShell: shell,\n\t\t\t},\n\t\t},\n\t}\n\terr := build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout})\n\tassert.NoError(t, err)\n\n\tbuild.GetBuildResponse.AllowGitFetch = true\n\tioutil.WriteFile(build.BuildDir+\"\/.git\/index.lock\", []byte{}, os.ModeSticky)\n\n\terr = build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout})\n\tassert.NoError(t, err)\n}\n\nfunc TestShellBuildWithIndexLockBash(t *testing.T) {\n\trunBuildWithIndexLockForShell(t, \"bash\")\n}\n\nfunc TestShellBuildWithIndexLockCmd(t *testing.T) {\n\trunBuildWithIndexLockForShell(t, \"cmd\")\n}\n\nfunc TestShellBuildWithIndexLockPowershell(t *testing.T) {\n\trunBuildWithIndexLockForShell(t, \"powershell\")\n}\nRefactor shell executor testspackage shell_test\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\n\t\"gitlab.com\/gitlab-org\/gitlab-ci-multi-runner\/common\"\n\t\"gitlab.com\/gitlab-org\/gitlab-ci-multi-runner\/helpers\"\n)\n\nfunc onEachShell(t *testing.T, f func(t *testing.T, shell string)) {\n\tt.Run(\"bash\", func(t *testing.T) {\n\t\tif helpers.SkipIntegrationTests(t, \"bash\") {\n\t\t\tt.Skip()\n\t\t}\n\n\t\tf(t, \"bash\")\n\t})\n\n\tt.Run(\"cmd.exe\", func(t *testing.T) {\n\t\tif helpers.SkipIntegrationTests(t, \"cmd.exe\") {\n\t\t\tt.Skip()\n\t\t}\n\n\t\tf(t, \"cmd\")\n\t})\n\n\tt.Run(\"powershell.exe\", func(t *testing.T) {\n\t\tif helpers.SkipIntegrationTests(t, \"powershell.exe\") {\n\t\t\tt.Skip()\n\t\t}\n\n\t\tf(t, \"powershell\")\n\t})\n}\n\nfunc runBuildWithTrace(t *testing.T, build *common.Build, trace *common.Trace) error {\n\ttimeoutTimer := time.AfterFunc(10*time.Second, func() {\n\t\tt.Log(\"Timed out\")\n\t\tt.FailNow()\n\t})\n\tdefer timeoutTimer.Stop()\n\n\treturn build.Run(&common.Config{}, trace)\n}\n\nfunc runBuild(t *testing.T, build *common.Build) error {\n\treturn runBuildWithTrace(t, build, &common.Trace{Writer: os.Stdout})\n}\n\nfunc runBuildReturningOutput(t *testing.T, build *common.Build) (string, error) {\n\tbuf := bytes.NewBuffer(nil)\n\terr := runBuildWithTrace(t, build, &common.Trace{Writer: buf})\n\toutput := buf.String()\n\tt.Log(output)\n\n\treturn output, err\n}\n\nfunc newBuild(t *testing.T, getBuildResponse common.GetBuildResponse, shell string) (*common.Build, func()) {\n\tdir, err := ioutil.TempDir(\"\", \"gitlab-runner-shell-executor-test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(\"Build directory:\", dir)\n\n\tbuild := &common.Build{\n\t\tGetBuildResponse: getBuildResponse,\n\t\tRunner: &common.RunnerConfig{\n\t\t\tRunnerSettings: common.RunnerSettings{\n\t\t\t\tBuildsDir: dir,\n\t\t\t\tExecutor: \"shell\",\n\t\t\t\tShell: shell,\n\t\t\t},\n\t\t},\n\t\tSystemInterrupt: make(chan os.Signal, 1),\n\t}\n\n\tcleanup := func() {\n\t\tos.RemoveAll(dir)\n\t}\n\n\treturn build, cleanup\n}\n\nfunc TestBuildSuccess(t *testing.T) {\n\tonEachShell(t, func(t *testing.T, shell string) {\n\t\tbuild, cleanup := newBuild(t, common.SuccessfulBuild, shell)\n\t\tdefer cleanup()\n\n\t\terr := runBuild(t, build)\n\t\tassert.NoError(t, err)\n\t})\n}\n\nfunc TestBuildAbort(t *testing.T) {\n\tonEachShell(t, func(t *testing.T, shell string) {\n\t\tbuild, cleanup := newBuild(t, common.LongRunningBuild, shell)\n\t\tdefer cleanup()\n\n\t\tabortTimer := time.AfterFunc(time.Second, func() {\n\t\t\tt.Log(\"Interrupt\")\n\t\t\tbuild.SystemInterrupt <- os.Interrupt\n\t\t})\n\t\tdefer abortTimer.Stop()\n\n\t\terr := runBuild(t, build)\n\t\tassert.EqualError(t, err, \"aborted: interrupt\")\n\t})\n}\n\nfunc TestBuildCancel(t *testing.T) {\n\tonEachShell(t, func(t *testing.T, shell string) {\n\t\tbuild, cleanup := newBuild(t, common.LongRunningBuild, shell)\n\t\tdefer cleanup()\n\n\t\tcancelChan := make(chan interface{}, 1)\n\t\tcancelTimer := time.AfterFunc(time.Second, func() {\n\t\t\tt.Log(\"Cancel\")\n\t\t\tcancelChan <- true\n\t\t})\n\t\tdefer cancelTimer.Stop()\n\n\t\terr := runBuildWithTrace(t, build, &common.Trace{Writer: os.Stdout, Abort: cancelChan})\n\t\tassert.EqualError(t, err, \"canceled\")\n\t\tassert.IsType(t, err, &common.BuildError{})\n\t})\n}\n\nfunc TestBuildWithIndexLock(t *testing.T) {\n\tonEachShell(t, func(t *testing.T, shell string) {\n\t\tbuild, cleanup := newBuild(t, common.SuccessfulBuild, shell)\n\t\tdefer cleanup()\n\n\t\terr := runBuild(t, build)\n\t\tassert.NoError(t, err)\n\n\t\tbuild.GetBuildResponse.AllowGitFetch = true\n\t\tioutil.WriteFile(build.BuildDir+\"\/.git\/index.lock\", []byte{}, os.ModeSticky)\n\n\t\terr = runBuild(t, build)\n\t\tassert.NoError(t, err)\n\t})\n}\n<|endoftext|>"} {"text":"package nyb\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tkitty \"github.com\/ugjka\/kittybot\"\n\t\"gopkg.in\/ugjka\/go-tz.v2\/tz\"\n)\n\nconst helpMsg = \"COMMANDS: '%shny ', '%stime ', '%snext', '%sprevious', '%sremaining', '%shelp', '%ssource'\"\n\nfunc (bot *Settings) addTriggers() {\n\tirc := bot.irc\n\n\t\/\/Log Notices\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"NOTICE\"\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"[NOTICE] \" + m.Content)\n\t\t},\n\t})\n\n\t\/\/Trigger for !source\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"source\")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Reply(m, \"https:\/\/github.com\/ugjka\/newyearsbot\")\n\t\t},\n\t})\n\n\t\/\/Trigger for !help\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"help\") ||\n\t\t\t\tnormalize(m.Content) == bot.Prefix+\"hny\"\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying help...\")\n\t\t\tb.Reply(m, fmt.Sprintf(helpMsg, bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix))\n\t\t},\n\t})\n\n\t\/\/Trigger for !next\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"next\")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying next...\")\n\t\t\tdur := time.Minute * time.Duration(bot.next.Offset*60)\n\t\t\tif timeNow().UTC().Add(dur).After(target) {\n\t\t\t\tb.Reply(m, fmt.Sprintf(\"No more next, %d is here AoE\", target.Year()))\n\t\t\t\treturn\n\t\t\t}\n\t\t\thdur := humanDur(target.Sub(timeNow().UTC().Add(dur)))\n\t\t\tb.Reply(m, fmt.Sprintf(\"Next New Year in %s in %s\",\n\t\t\t\thdur, bot.next))\n\t\t},\n\t})\n\n\t\/\/Trigger for !previous\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"previous\")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying previous...\")\n\t\t\tdur := time.Minute * time.Duration(bot.previous.Offset*60)\n\t\t\thdur := humanDur(timeNow().UTC().Add(dur).Sub(target))\n\t\t\tif bot.previous.Offset == -12 {\n\t\t\t\thdur = humanDur(timeNow().UTC().Add(dur).Sub(target.AddDate(-1, 0, 0)))\n\t\t\t}\n\t\t\tb.Reply(m, fmt.Sprintf(\"Previous New Year %s ago in %s\",\n\t\t\t\thdur, bot.previous))\n\t\t},\n\t})\n\n\t\/\/Trigger for !remaining\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"remaining\")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying remaining...\")\n\t\t\tplural := \"s\"\n\t\t\tif bot.remaining == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tb.Reply(m, fmt.Sprintf(\"%d timezone%s remaining. %d%% are in the new year\", bot.remaining, (bot.zones - bot.remaining) \/ bot.zones, plural))\n\t\t},\n\t})\n\n\t\/\/Trigger for time in location\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"time \")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying time...\")\n\t\t\tresult, err := bot.time(normalize(m.Content)[len(bot.Prefix)+len(\"time\")+1:])\n\t\t\tif err == errNoZone || err == errNoPlace {\n\t\t\t\tb.Warn(\"Query error: \" + err.Error())\n\t\t\t\tb.Reply(m, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tb.Warn(\"Query error: \" + err.Error())\n\t\t\t\tb.Reply(m, \"Some error occurred!\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tb.Reply(m, result)\n\t\t},\n\t})\n\n\t\/\/Trigger for UTC time\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tnormalize(m.Content) == bot.Prefix+\"time\"\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying time...\")\n\t\t\tresult := \"Time is \" + time.Now().UTC().Format(\"Mon Jan 2 15:04:05 -0700 MST 2006\")\n\t\t\tb.Reply(m, result)\n\t\t},\n\t})\n\n\t\/\/Trigger for new year in location\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"hny \")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tresult, err := bot.newYear(normalize(m.Content)[len(bot.Prefix)+len(\"hny\")+1:])\n\t\t\tif err == errNoZone || err == errNoPlace {\n\t\t\t\tb.Warn(\"Query error: \" + err.Error())\n\t\t\t\tb.Reply(m, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tb.Warn(\"Query error: \" + err.Error())\n\t\t\t\tb.Reply(m, \"Some error occurred!\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tb.Reply(m, result)\n\t\t},\n\t})\n}\n\nvar (\n\terrNoZone = errors.New(\"couldn't get timezone for that location\")\n\terrNoPlace = errors.New(\"Couldn't find that place\")\n)\n\nfunc (bot *Settings) time(location string) (string, error) {\n\tbot.irc.Info(\"Querying location: \" + location)\n\tdata, err := NominatimFetcher(&bot.Email, &bot.Nominatim, &location)\n\tif err != nil {\n\t\tbot.irc.Warn(\"Nominatim error: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\tvar res NominatimResults\n\tif err = json.Unmarshal(data, &res); err != nil {\n\t\tbot.irc.Warn(\"Nominatim JSON error: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\tif len(res) == 0 {\n\t\treturn \"\", errNoPlace\n\t}\n\tp := tz.Point{\n\t\tLat: res[0].Lat,\n\t\tLon: res[0].Lon,\n\t}\n\ttzid, err := tz.GetZone(p)\n\tif err != nil {\n\t\treturn \"\", errNoZone\n\t}\n\tzone, err := time.LoadLocation(tzid[0])\n\tif err != nil {\n\t\treturn \"\", errNoZone\n\t}\n\taddress := res[0].DisplayName\n\tmsg := fmt.Sprintf(\"Time in %s is %s\", address, time.Now().In(zone).Format(\"Mon Jan 2 15:04:05 -0700 MST 2006\"))\n\treturn msg, nil\n}\n\nfunc (bot *Settings) newYear(location string) (string, error) {\n\tbot.irc.Info(\"Querying location: \" + location)\n\tdata, err := NominatimFetcher(&bot.Email, &bot.Nominatim, &location)\n\tif err != nil {\n\t\tbot.irc.Warn(\"Nominatim error: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\tvar res NominatimResults\n\tif err = json.Unmarshal(data, &res); err != nil {\n\t\tbot.irc.Warn(\"Nominatim JSON error: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\tif len(res) == 0 {\n\t\treturn \"\", errNoPlace\n\t}\n\tp := tz.Point{\n\t\tLat: res[0].Lat,\n\t\tLon: res[0].Lon,\n\t}\n\ttzid, err := tz.GetZone(p)\n\tif err != nil {\n\t\treturn \"\", errNoZone\n\t}\n\tzone, err := time.LoadLocation(tzid[0])\n\tif err != nil {\n\t\treturn \"\", errNoZone\n\t}\n\toffset := zoneOffset(target, zone)\n\taddress := res[0].DisplayName\n\tif timeNow().UTC().Add(offset).Before(target) {\n\t\thdur := humanDur(target.Sub(timeNow().UTC().Add(offset)))\n\t\tconst newYearFutureMsg = \"New Year in %s will happen in %s\"\n\t\treturn fmt.Sprintf(newYearFutureMsg, address, hdur), nil\n\t}\n\thdur := humanDur(timeNow().UTC().Add(offset).Sub(target))\n\tconst newYearPastMsg = \"New Year in %s happened %s ago\"\n\treturn fmt.Sprintf(newYearPastMsg, address, hdur), nil\n}\nmultiply for percentage intpackage nyb\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tkitty \"github.com\/ugjka\/kittybot\"\n\t\"gopkg.in\/ugjka\/go-tz.v2\/tz\"\n)\n\nconst helpMsg = \"COMMANDS: '%shny ', '%stime ', '%snext', '%sprevious', '%sremaining', '%shelp', '%ssource'\"\n\nfunc (bot *Settings) addTriggers() {\n\tirc := bot.irc\n\n\t\/\/Log Notices\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"NOTICE\"\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"[NOTICE] \" + m.Content)\n\t\t},\n\t})\n\n\t\/\/Trigger for !source\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"source\")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Reply(m, \"https:\/\/github.com\/ugjka\/newyearsbot\")\n\t\t},\n\t})\n\n\t\/\/Trigger for !help\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"help\") ||\n\t\t\t\tnormalize(m.Content) == bot.Prefix+\"hny\"\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying help...\")\n\t\t\tb.Reply(m, fmt.Sprintf(helpMsg, bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix, bot.Prefix))\n\t\t},\n\t})\n\n\t\/\/Trigger for !next\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"next\")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying next...\")\n\t\t\tdur := time.Minute * time.Duration(bot.next.Offset*60)\n\t\t\tif timeNow().UTC().Add(dur).After(target) {\n\t\t\t\tb.Reply(m, fmt.Sprintf(\"No more next, %d is here AoE\", target.Year()))\n\t\t\t\treturn\n\t\t\t}\n\t\t\thdur := humanDur(target.Sub(timeNow().UTC().Add(dur)))\n\t\t\tb.Reply(m, fmt.Sprintf(\"Next New Year in %s in %s\",\n\t\t\t\thdur, bot.next))\n\t\t},\n\t})\n\n\t\/\/Trigger for !previous\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"previous\")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying previous...\")\n\t\t\tdur := time.Minute * time.Duration(bot.previous.Offset*60)\n\t\t\thdur := humanDur(timeNow().UTC().Add(dur).Sub(target))\n\t\t\tif bot.previous.Offset == -12 {\n\t\t\t\thdur = humanDur(timeNow().UTC().Add(dur).Sub(target.AddDate(-1, 0, 0)))\n\t\t\t}\n\t\t\tb.Reply(m, fmt.Sprintf(\"Previous New Year %s ago in %s\",\n\t\t\t\thdur, bot.previous))\n\t\t},\n\t})\n\n\t\/\/Trigger for !remaining\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"remaining\")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying remaining...\")\n\t\t\tplural := \"s\"\n\t\t\tif bot.remaining == 1 {\n\t\t\t\tplural = \"\"\n\t\t\t}\n\t\t\tb.Reply(m, fmt.Sprintf(\"%d timezone%s remaining. %d%% are in the new year\", bot.remaining, (bot.zones - bot.remaining) * 100 \/ (bot.zones * 100), plural))\n\t\t},\n\t})\n\n\t\/\/Trigger for time in location\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"time \")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying time...\")\n\t\t\tresult, err := bot.time(normalize(m.Content)[len(bot.Prefix)+len(\"time\")+1:])\n\t\t\tif err == errNoZone || err == errNoPlace {\n\t\t\t\tb.Warn(\"Query error: \" + err.Error())\n\t\t\t\tb.Reply(m, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tb.Warn(\"Query error: \" + err.Error())\n\t\t\t\tb.Reply(m, \"Some error occurred!\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tb.Reply(m, result)\n\t\t},\n\t})\n\n\t\/\/Trigger for UTC time\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tnormalize(m.Content) == bot.Prefix+\"time\"\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tb.Info(\"Querying time...\")\n\t\t\tresult := \"Time is \" + time.Now().UTC().Format(\"Mon Jan 2 15:04:05 -0700 MST 2006\")\n\t\t\tb.Reply(m, result)\n\t\t},\n\t})\n\n\t\/\/Trigger for new year in location\n\tirc.AddTrigger(kitty.Trigger{\n\t\tCondition: func(b *kitty.Bot, m *kitty.Message) bool {\n\t\t\treturn m.Command == \"PRIVMSG\" &&\n\t\t\t\tstrings.HasPrefix(normalize(m.Content), bot.Prefix+\"hny \")\n\t\t},\n\t\tAction: func(b *kitty.Bot, m *kitty.Message) {\n\t\t\tresult, err := bot.newYear(normalize(m.Content)[len(bot.Prefix)+len(\"hny\")+1:])\n\t\t\tif err == errNoZone || err == errNoPlace {\n\t\t\t\tb.Warn(\"Query error: \" + err.Error())\n\t\t\t\tb.Reply(m, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tb.Warn(\"Query error: \" + err.Error())\n\t\t\t\tb.Reply(m, \"Some error occurred!\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tb.Reply(m, result)\n\t\t},\n\t})\n}\n\nvar (\n\terrNoZone = errors.New(\"couldn't get timezone for that location\")\n\terrNoPlace = errors.New(\"Couldn't find that place\")\n)\n\nfunc (bot *Settings) time(location string) (string, error) {\n\tbot.irc.Info(\"Querying location: \" + location)\n\tdata, err := NominatimFetcher(&bot.Email, &bot.Nominatim, &location)\n\tif err != nil {\n\t\tbot.irc.Warn(\"Nominatim error: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\tvar res NominatimResults\n\tif err = json.Unmarshal(data, &res); err != nil {\n\t\tbot.irc.Warn(\"Nominatim JSON error: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\tif len(res) == 0 {\n\t\treturn \"\", errNoPlace\n\t}\n\tp := tz.Point{\n\t\tLat: res[0].Lat,\n\t\tLon: res[0].Lon,\n\t}\n\ttzid, err := tz.GetZone(p)\n\tif err != nil {\n\t\treturn \"\", errNoZone\n\t}\n\tzone, err := time.LoadLocation(tzid[0])\n\tif err != nil {\n\t\treturn \"\", errNoZone\n\t}\n\taddress := res[0].DisplayName\n\tmsg := fmt.Sprintf(\"Time in %s is %s\", address, time.Now().In(zone).Format(\"Mon Jan 2 15:04:05 -0700 MST 2006\"))\n\treturn msg, nil\n}\n\nfunc (bot *Settings) newYear(location string) (string, error) {\n\tbot.irc.Info(\"Querying location: \" + location)\n\tdata, err := NominatimFetcher(&bot.Email, &bot.Nominatim, &location)\n\tif err != nil {\n\t\tbot.irc.Warn(\"Nominatim error: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\tvar res NominatimResults\n\tif err = json.Unmarshal(data, &res); err != nil {\n\t\tbot.irc.Warn(\"Nominatim JSON error: \" + err.Error())\n\t\treturn \"\", err\n\t}\n\tif len(res) == 0 {\n\t\treturn \"\", errNoPlace\n\t}\n\tp := tz.Point{\n\t\tLat: res[0].Lat,\n\t\tLon: res[0].Lon,\n\t}\n\ttzid, err := tz.GetZone(p)\n\tif err != nil {\n\t\treturn \"\", errNoZone\n\t}\n\tzone, err := time.LoadLocation(tzid[0])\n\tif err != nil {\n\t\treturn \"\", errNoZone\n\t}\n\toffset := zoneOffset(target, zone)\n\taddress := res[0].DisplayName\n\tif timeNow().UTC().Add(offset).Before(target) {\n\t\thdur := humanDur(target.Sub(timeNow().UTC().Add(offset)))\n\t\tconst newYearFutureMsg = \"New Year in %s will happen in %s\"\n\t\treturn fmt.Sprintf(newYearFutureMsg, address, hdur), nil\n\t}\n\thdur := humanDur(timeNow().UTC().Add(offset).Sub(target))\n\tconst newYearPastMsg = \"New Year in %s happened %s ago\"\n\treturn fmt.Sprintf(newYearPastMsg, address, hdur), nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017, 2020, Oracle and\/or its affiliates. All rights reserved.\n\/\/ Licensed under the Mozilla Public License v2.0\n\npackage oci\n\nimport (\n\t\"log\"\n)\n\nconst Version = \"3.88.0\"\n\nfunc PrintVersion() {\n\tlog.Printf(\"[INFO] terraform-provider-oci %s\\n\", Version)\n}\nFinalize changelog and release for version v3.89.0\/\/ Copyright (c) 2017, 2020, Oracle and\/or its affiliates. All rights reserved.\n\/\/ Licensed under the Mozilla Public License v2.0\n\npackage oci\n\nimport (\n\t\"log\"\n)\n\nconst Version = \"3.89.0\"\n\nfunc PrintVersion() {\n\tlog.Printf(\"[INFO] terraform-provider-oci %s\\n\", Version)\n}\n<|endoftext|>"} {"text":"package stl\n\n\/\/ This file defines the top level reading and writing operations\n\/\/ for the stl package\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n)\n\n\/\/ ErrIncompleteBinaryHeader is used when reading binary STL files with incomplete header.\nvar ErrIncompleteBinaryHeader = errors.New(\"incomplete STL binary header, 84 bytes expected\")\n\n\/\/ ErrUnexpectedEOF is used by ReadFile and ReadAll to signify an incomplete file.\nvar ErrUnexpectedEOF = errors.New(\"unexpected end of file\")\n\n\/\/ ReadFile reads the contents of a file into a new Solid object. The file\n\/\/ can be either in STL ASCII format, beginning with \"solid \", or in\n\/\/ STL binary format, beginning with a 84 byte header. Shorthand for os.Open and ReadAll\nfunc ReadFile(filename string) (solid *Solid, err error) {\n\tvar s Solid\n\terr = CopyFile(filename, &s)\n\tif err == nil {\n\t\tsolid = &s\n\t}\n\treturn\n}\n\n\/\/ ReadAll reads the contents of a file into a new Solid object. The file\n\/\/ can be either in STL ASCII format, beginning with \"solid \", or in\n\/\/ STL binary format, beginning with a 84 byte header. Because of this,\n\/\/ the file pointer has to be at the beginning of the file.\nfunc ReadAll(r io.ReadSeeker) (solid *Solid, err error) {\n\tvar s Solid\n\terr = CopyAll(r, &s)\n\tif err == nil {\n\t\tsolid = &s\n\t}\n\treturn\n}\n\nfunc CopyFile(filename string, sw Writer) (err error) {\n\tfile, openErr := os.Open(filename)\n\tif openErr != nil {\n\t\terr = openErr\n\t\treturn\n\t}\n\terr = CopyAll(file, sw)\n\tcloseErr := file.Close()\n\tif err == nil {\n\t\terr = closeErr\n\t}\n\treturn\n}\n\nfunc CopyAll(r io.ReadSeeker, sw Writer) (err error) {\n\tisBinary, err := isBinaryFile(r)\n\tif err != nil {\n\t\treturn\n\t}\n\tif _, err = r.Seek(0, io.SeekStart); err != nil {\n\t\treturn\n\t}\n\n\tif isBinary {\n\t\tsw.SetASCII(false)\n\t\terr = readAllBinary(r, sw)\n\t} else {\n\t\tsw.SetASCII(true)\n\t\terr = readAllASCII(r, sw)\n\t}\n\n\treturn\n}\n\n\/\/ isBinaryFile returns true if the seekable stream tests as a binary file by\n\/\/ matching triangle count (in header) and file size\nfunc isBinaryFile(r io.ReadSeeker) (isBinary bool, err error) {\n\tvar header [binaryHeaderSize]byte\n\t_, err = r.Read(header[:])\n\tif err != nil {\n\t\tif err == io.EOF { \/\/ too short to meet spec\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\t}\n\ttriangleCount := triangleCountFromBinaryHeader(header[:])\n\texpectedFileLength := int64(triangleCount)*binaryTriangleSize + binaryHeaderSize\n\tactualFileLength, err := r.Seek(0, io.SeekEnd)\n\tif err != nil {\n\t\treturn\n\t}\n\tisBinary = expectedFileLength == actualFileLength\n\treturn\n}\n\n\/\/ WriteFile creates file with name filename and write contents of this Solid.\n\/\/ Shorthand for os.Create and Solid.WriteAll\nfunc (s *Solid) WriteFile(filename string) (err error) {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbufWriter := bufio.NewWriter(file)\n\terr = s.WriteAll(bufWriter)\n\tflushErr := bufWriter.Flush()\n\tcloseErr := file.Close()\n\tif err == nil {\n\t\terr = flushErr\n\t}\n\tif err == nil {\n\t\terr = closeErr\n\t}\n\treturn\n}\n\n\/\/ WriteAll writes the contents of this solid to an io.Writer. Depending on solid.IsAscii\n\/\/ the STL ASCII format, or the STL binary format is used. If IsAscii\n\/\/ is false, and the binary format is used, solid.Name will be used for\n\/\/ the header, if solid.BinaryHeader is empty.\nfunc (s *Solid) WriteAll(w io.Writer) error {\n\tif s.IsAscii {\n\t\treturn writeSolidASCII(w, s)\n\t}\n\treturn writeSolidBinary(w, s)\n}\n\n\/\/ Extracts an ASCII string from a byte slice. Reads all characters\n\/\/ from the beginning until a \\0 or a non-ASCII character is found.\nfunc extractASCIIString(byteData []byte) string {\n\ti := 0\n\tfor i < len(byteData) && byteData[i] < byte(128) && byteData[i] != byte(0) {\n\t\ti++\n\t}\n\treturn string(byteData[0:i])\n}\nuse bufio.Reader for reading STL files for speed-up (works best on binary)package stl\n\n\/\/ This file defines the top level reading and writing operations\n\/\/ for the stl package\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n)\n\n\/\/ ErrIncompleteBinaryHeader is used when reading binary STL files with incomplete header.\nvar ErrIncompleteBinaryHeader = errors.New(\"incomplete STL binary header, 84 bytes expected\")\n\n\/\/ ErrUnexpectedEOF is used by ReadFile and ReadAll to signify an incomplete file.\nvar ErrUnexpectedEOF = errors.New(\"unexpected end of file\")\n\n\/\/ ReadFile reads the contents of a file into a new Solid object. The file\n\/\/ can be either in STL ASCII format, beginning with \"solid \", or in\n\/\/ STL binary format, beginning with a 84 byte header. Shorthand for os.Open and ReadAll\nfunc ReadFile(filename string) (solid *Solid, err error) {\n\tvar s Solid\n\terr = CopyFile(filename, &s)\n\tif err == nil {\n\t\tsolid = &s\n\t}\n\treturn\n}\n\n\/\/ ReadAll reads the contents of a file into a new Solid object. The file\n\/\/ can be either in STL ASCII format, beginning with \"solid \", or in\n\/\/ STL binary format, beginning with a 84 byte header. Because of this,\n\/\/ the file pointer has to be at the beginning of the file.\nfunc ReadAll(r io.ReadSeeker) (solid *Solid, err error) {\n\tvar s Solid\n\terr = CopyAll(r, &s)\n\tif err == nil {\n\t\tsolid = &s\n\t}\n\treturn\n}\n\nfunc CopyFile(filename string, sw Writer) (err error) {\n\tfile, openErr := os.Open(filename)\n\tif openErr != nil {\n\t\terr = openErr\n\t\treturn\n\t}\n\terr = CopyAll(file, sw)\n\tcloseErr := file.Close()\n\tif err == nil {\n\t\terr = closeErr\n\t}\n\treturn\n}\n\nfunc CopyAll(r io.ReadSeeker, sw Writer) (err error) {\n\tisBinary, err := isBinaryFile(r)\n\tif err != nil {\n\t\treturn\n\t}\n\tif _, err = r.Seek(0, io.SeekStart); err != nil {\n\t\treturn\n\t}\n\tbr := bufio.NewReader(r)\n\n\tif isBinary {\n\t\tsw.SetASCII(false)\n\t\terr = readAllBinary(br, sw)\n\t} else {\n\t\tsw.SetASCII(true)\n\t\terr = readAllASCII(br, sw)\n\t}\n\n\treturn\n}\n\n\/\/ isBinaryFile returns true if the seekable stream tests as a binary file by\n\/\/ matching triangle count (in header) and file size\nfunc isBinaryFile(r io.ReadSeeker) (isBinary bool, err error) {\n\tvar header [binaryHeaderSize]byte\n\t_, err = r.Read(header[:])\n\tif err != nil {\n\t\tif err == io.EOF { \/\/ too short to meet spec\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\t}\n\ttriangleCount := triangleCountFromBinaryHeader(header[:])\n\texpectedFileLength := int64(triangleCount)*binaryTriangleSize + binaryHeaderSize\n\tactualFileLength, err := r.Seek(0, io.SeekEnd)\n\tif err != nil {\n\t\treturn\n\t}\n\tisBinary = expectedFileLength == actualFileLength\n\treturn\n}\n\n\/\/ WriteFile creates file with name filename and write contents of this Solid.\n\/\/ Shorthand for os.Create and Solid.WriteAll\nfunc (s *Solid) WriteFile(filename string) (err error) {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbufWriter := bufio.NewWriter(file)\n\terr = s.WriteAll(bufWriter)\n\tflushErr := bufWriter.Flush()\n\tcloseErr := file.Close()\n\tif err == nil {\n\t\terr = flushErr\n\t}\n\tif err == nil {\n\t\terr = closeErr\n\t}\n\treturn\n}\n\n\/\/ WriteAll writes the contents of this solid to an io.Writer. Depending on solid.IsAscii\n\/\/ the STL ASCII format, or the STL binary format is used. If IsAscii\n\/\/ is false, and the binary format is used, solid.Name will be used for\n\/\/ the header, if solid.BinaryHeader is empty.\nfunc (s *Solid) WriteAll(w io.Writer) error {\n\tif s.IsAscii {\n\t\treturn writeSolidASCII(w, s)\n\t}\n\treturn writeSolidBinary(w, s)\n}\n\n\/\/ Extracts an ASCII string from a byte slice. Reads all characters\n\/\/ from the beginning until a \\0 or a non-ASCII character is found.\nfunc extractASCIIString(byteData []byte) string {\n\ti := 0\n\tfor i < len(byteData) && byteData[i] < byte(128) && byteData[i] != byte(0) {\n\t\ti++\n\t}\n\treturn string(byteData[0:i])\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/flynn\/flynn\/controller\/client\"\n\tct \"github.com\/flynn\/flynn\/controller\/types\"\n\t\"github.com\/flynn\/flynn\/discoverd\/client\"\n\t\"github.com\/flynn\/flynn\/pkg\/cluster\"\n\t\"github.com\/flynn\/flynn\/pkg\/exec\"\n\t\"github.com\/flynn\/flynn\/pkg\/random\"\n)\n\nvar clusterc *cluster.Client\n\nfunc init() {\n\tlog.SetFlags(0)\n\n\tvar err error\n\tclusterc, err = cluster.NewClient()\n\tif err != nil {\n\t\tlog.Fatalln(\"Error connecting to cluster leader:\", err)\n\t}\n}\n\nvar typesPattern = regexp.MustCompile(\"types.* -> (.+)\\n\")\n\nfunc main() {\n\tclient, err := controller.NewClient(\"\", os.Getenv(\"CONTROLLER_AUTH_KEY\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to connect to controller:\", err)\n\t}\n\t\/\/ TODO: use discoverd http dialer here?\n\tservices, err := discoverd.Services(\"blobstore\", discoverd.DefaultTimeout)\n\tif err != nil || len(services) < 1 {\n\t\tlog.Fatalf(\"Unable to discover blobstore %q\", err)\n\t}\n\tblobstoreHost := services[0].Addr\n\n\tappName := os.Args[1]\n\n\tapp, err := client.GetApp(appName)\n\tif err == controller.ErrNotFound {\n\t\tlog.Fatalf(\"Unknown app %q\", appName)\n\t} else if err != nil {\n\t\tlog.Fatalln(\"Error retrieving app:\", err)\n\t}\n\tprevRelease, err := client.GetAppRelease(app.Name)\n\tif err == controller.ErrNotFound {\n\t\tprevRelease = &ct.Release{}\n\t} else if err != nil {\n\t\tlog.Fatalln(\"Error getting current app release:\", err)\n\t}\n\n\tfmt.Printf(\"-----> Building %s...\\n\", app.Name)\n\n\tvar output bytes.Buffer\n\tslugURL := fmt.Sprintf(\"http:\/\/%s\/%s.tgz\", blobstoreHost, random.UUID())\n\tcmd := exec.Command(exec.DockerImage(\"flynn\/slugbuilder\", os.Getenv(\"SLUGBUILDER_IMAGE_ID\")), slugURL)\n\tcmd.Stdout = io.MultiWriter(os.Stdout, &output)\n\tcmd.Stderr = os.Stderr\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tgo appendEnvDir(os.Stdin, stdin, prevRelease.Env)\n\tif buildpackURL, ok := prevRelease.Env[\"BUILDPACK_URL\"]; ok {\n\t\tcmd.Env = map[string]string{\"BUILDPACK_URL\": buildpackURL}\n\t}\n\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Fatalln(\"Build failed:\", err)\n\t}\n\n\tvar types []string\n\tif match := typesPattern.FindSubmatch(output.Bytes()); match != nil {\n\t\ttypes = strings.Split(string(match[1]), \", \")\n\t}\n\n\tfmt.Printf(\"-----> Creating release...\\n\")\n\n\tartifact := &ct.Artifact{Type: \"docker\", URI: \"https:\/\/registry.hub.docker.com\/flynn\/slugrunner?id=\" + os.Getenv(\"SLUGRUNNER_IMAGE_ID\")}\n\tif err := client.CreateArtifact(artifact); err != nil {\n\t\tlog.Fatalln(\"Error creating artifact:\", err)\n\t}\n\n\trelease := &ct.Release{\n\t\tArtifactID: artifact.ID,\n\t\tEnv: prevRelease.Env,\n\t}\n\tprocs := make(map[string]ct.ProcessType)\n\tfor _, t := range types {\n\t\tproc := prevRelease.Processes[t]\n\t\tproc.Cmd = []string{\"start\", t}\n\t\tif t == \"web\" {\n\t\t\tproc.Ports = []ct.Port{{Proto: \"tcp\"}}\n\t\t\tif proc.Env == nil {\n\t\t\t\tproc.Env = make(map[string]string)\n\t\t\t}\n\t\t\tproc.Env[\"SD_NAME\"] = app.Name + \"-web\"\n\t\t}\n\t\tprocs[t] = proc\n\t}\n\trelease.Processes = procs\n\tif release.Env == nil {\n\t\trelease.Env = make(map[string]string)\n\t}\n\trelease.Env[\"SLUG_URL\"] = slugURL\n\n\tif err := client.CreateRelease(release); err != nil {\n\t\tlog.Fatalln(\"Error creating release:\", err)\n\t}\n\tif err := client.SetAppRelease(app.Name, release.ID); err != nil {\n\t\tlog.Fatalln(\"Error setting app release:\", err)\n\t}\n\n\tfmt.Println(\"=====> Application deployed\")\n\n\t\/\/ If the app is new and the web process type exists,\n\t\/\/ it should scale to one process after the release is created.\n\tif _, ok := procs[\"web\"]; ok && prevRelease.ID == \"\" {\n\t\tformation := &ct.Formation{\n\t\t\tAppID: app.ID,\n\t\t\tReleaseID: release.ID,\n\t\t\tProcesses: map[string]int{\"web\": 1},\n\t\t}\n\t\tif err := client.PutFormation(formation); err != nil {\n\t\t\tlog.Fatalln(\"Error putting formation:\", err)\n\t\t}\n\n\t\tfmt.Println(\"=====> Added default web=1 formation\")\n\t}\n}\n\nfunc appendEnvDir(stdin io.Reader, pipe io.WriteCloser, env map[string]string) {\n\tdefer pipe.Close()\n\ttr := tar.NewReader(stdin)\n\ttw := tar.NewWriter(pipe)\n\tfor {\n\t\thdr, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\t\/\/ end of tar archive\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\thdr.Name = path.Join(\"app\", hdr.Name)\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := io.Copy(tw, tr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\t\/\/ append env dir\n\tfor key, value := range env {\n\t\thdr := &tar.Header{\n\t\t\tName: path.Join(\"env\", key),\n\t\t\tMode: 0400,\n\t\t\tModTime: time.Now(),\n\t\t\tSize: int64(len(value)),\n\t\t}\n\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := tw.Write([]byte(value)); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\thdr := &tar.Header{\n\t\tName: \".ENV_DIR_bdca46b87df0537eaefe79bb632d37709ff1df18\",\n\t\tMode: 0400,\n\t\tModTime: time.Now(),\n\t\tSize: 0,\n\t}\n\tif err := tw.WriteHeader(hdr); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\nreceiver: Only append ENV dir if non-emptypackage main\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/flynn\/flynn\/controller\/client\"\n\tct \"github.com\/flynn\/flynn\/controller\/types\"\n\t\"github.com\/flynn\/flynn\/discoverd\/client\"\n\t\"github.com\/flynn\/flynn\/pkg\/cluster\"\n\t\"github.com\/flynn\/flynn\/pkg\/exec\"\n\t\"github.com\/flynn\/flynn\/pkg\/random\"\n)\n\nvar clusterc *cluster.Client\n\nfunc init() {\n\tlog.SetFlags(0)\n\n\tvar err error\n\tclusterc, err = cluster.NewClient()\n\tif err != nil {\n\t\tlog.Fatalln(\"Error connecting to cluster leader:\", err)\n\t}\n}\n\nvar typesPattern = regexp.MustCompile(\"types.* -> (.+)\\n\")\n\nfunc main() {\n\tclient, err := controller.NewClient(\"\", os.Getenv(\"CONTROLLER_AUTH_KEY\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to connect to controller:\", err)\n\t}\n\t\/\/ TODO: use discoverd http dialer here?\n\tservices, err := discoverd.Services(\"blobstore\", discoverd.DefaultTimeout)\n\tif err != nil || len(services) < 1 {\n\t\tlog.Fatalf(\"Unable to discover blobstore %q\", err)\n\t}\n\tblobstoreHost := services[0].Addr\n\n\tappName := os.Args[1]\n\n\tapp, err := client.GetApp(appName)\n\tif err == controller.ErrNotFound {\n\t\tlog.Fatalf(\"Unknown app %q\", appName)\n\t} else if err != nil {\n\t\tlog.Fatalln(\"Error retrieving app:\", err)\n\t}\n\tprevRelease, err := client.GetAppRelease(app.Name)\n\tif err == controller.ErrNotFound {\n\t\tprevRelease = &ct.Release{}\n\t} else if err != nil {\n\t\tlog.Fatalln(\"Error getting current app release:\", err)\n\t}\n\n\tfmt.Printf(\"-----> Building %s...\\n\", app.Name)\n\n\tvar output bytes.Buffer\n\tslugURL := fmt.Sprintf(\"http:\/\/%s\/%s.tgz\", blobstoreHost, random.UUID())\n\tcmd := exec.Command(exec.DockerImage(\"flynn\/slugbuilder\", os.Getenv(\"SLUGBUILDER_IMAGE_ID\")), slugURL)\n\tcmd.Stdout = io.MultiWriter(os.Stdout, &output)\n\tcmd.Stderr = os.Stderr\n\tif len(prevRelease.Env) > 0 {\n\t\tstdin, err := cmd.StdinPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tgo appendEnvDir(os.Stdin, stdin, prevRelease.Env)\n\t} else {\n\t\tcmd.Stdin = os.Stdin\n\t}\n\tif buildpackURL, ok := prevRelease.Env[\"BUILDPACK_URL\"]; ok {\n\t\tcmd.Env = map[string]string{\"BUILDPACK_URL\": buildpackURL}\n\t}\n\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Fatalln(\"Build failed:\", err)\n\t}\n\n\tvar types []string\n\tif match := typesPattern.FindSubmatch(output.Bytes()); match != nil {\n\t\ttypes = strings.Split(string(match[1]), \", \")\n\t}\n\n\tfmt.Printf(\"-----> Creating release...\\n\")\n\n\tartifact := &ct.Artifact{Type: \"docker\", URI: \"https:\/\/registry.hub.docker.com\/flynn\/slugrunner?id=\" + os.Getenv(\"SLUGRUNNER_IMAGE_ID\")}\n\tif err := client.CreateArtifact(artifact); err != nil {\n\t\tlog.Fatalln(\"Error creating artifact:\", err)\n\t}\n\n\trelease := &ct.Release{\n\t\tArtifactID: artifact.ID,\n\t\tEnv: prevRelease.Env,\n\t}\n\tprocs := make(map[string]ct.ProcessType)\n\tfor _, t := range types {\n\t\tproc := prevRelease.Processes[t]\n\t\tproc.Cmd = []string{\"start\", t}\n\t\tif t == \"web\" {\n\t\t\tproc.Ports = []ct.Port{{Proto: \"tcp\"}}\n\t\t\tif proc.Env == nil {\n\t\t\t\tproc.Env = make(map[string]string)\n\t\t\t}\n\t\t\tproc.Env[\"SD_NAME\"] = app.Name + \"-web\"\n\t\t}\n\t\tprocs[t] = proc\n\t}\n\trelease.Processes = procs\n\tif release.Env == nil {\n\t\trelease.Env = make(map[string]string)\n\t}\n\trelease.Env[\"SLUG_URL\"] = slugURL\n\n\tif err := client.CreateRelease(release); err != nil {\n\t\tlog.Fatalln(\"Error creating release:\", err)\n\t}\n\tif err := client.SetAppRelease(app.Name, release.ID); err != nil {\n\t\tlog.Fatalln(\"Error setting app release:\", err)\n\t}\n\n\tfmt.Println(\"=====> Application deployed\")\n\n\t\/\/ If the app is new and the web process type exists,\n\t\/\/ it should scale to one process after the release is created.\n\tif _, ok := procs[\"web\"]; ok && prevRelease.ID == \"\" {\n\t\tformation := &ct.Formation{\n\t\t\tAppID: app.ID,\n\t\t\tReleaseID: release.ID,\n\t\t\tProcesses: map[string]int{\"web\": 1},\n\t\t}\n\t\tif err := client.PutFormation(formation); err != nil {\n\t\t\tlog.Fatalln(\"Error putting formation:\", err)\n\t\t}\n\n\t\tfmt.Println(\"=====> Added default web=1 formation\")\n\t}\n}\n\nfunc appendEnvDir(stdin io.Reader, pipe io.WriteCloser, env map[string]string) {\n\tdefer pipe.Close()\n\ttr := tar.NewReader(stdin)\n\ttw := tar.NewWriter(pipe)\n\tfor {\n\t\thdr, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\t\/\/ end of tar archive\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\thdr.Name = path.Join(\"app\", hdr.Name)\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := io.Copy(tw, tr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\t\/\/ append env dir\n\tfor key, value := range env {\n\t\thdr := &tar.Header{\n\t\t\tName: path.Join(\"env\", key),\n\t\t\tMode: 0400,\n\t\t\tModTime: time.Now(),\n\t\t\tSize: int64(len(value)),\n\t\t}\n\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := tw.Write([]byte(value)); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\thdr := &tar.Header{\n\t\tName: \".ENV_DIR_bdca46b87df0537eaefe79bb632d37709ff1df18\",\n\t\tMode: 0400,\n\t\tModTime: time.Now(),\n\t\tSize: 0,\n\t}\n\tif err := tw.WriteHeader(hdr); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n<|endoftext|>"} {"text":"package anaconda_test\n\nimport (\n\t\"net\/url\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/ChimeraCoder\/anaconda\"\n)\n\nfunc TestOEmbed(t *testing.T) {\n\t\/\/ It is the only one that can be tested without auth\n\tapi := anaconda.NewTwitterApi(\"\", \"\")\n\to, err := api.GetOEmbed(url.Values{\"id\": []string{\"99530515043983360\"}})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif !reflect.DeepEqual(o, expectedOEmbed) {\n\t\tt.Error(\"Actual OEmbed differs from expected\", o)\n\t}\n}\n\nvar expectedOEmbed anaconda.OEmbed = anaconda.OEmbed{\n\tCache_age: \"3153600000\",\n\tUrl: \"https:\/\/twitter.com\/twitter\/statuses\/99530515043983360\",\n\tHeight: 0,\n\tProvider_url: \"https:\/\/twitter.com\",\n\tProvider_name: \"Twitter\",\n\tAuthor_name: \"Twitter\",\n\tVersion: \"1.0\",\n\tAuthor_url: \"https:\/\/twitter.com\/twitter\",\n\tType: \"rich\",\n\tHtml: \"\\u003Cblockquote class=\\\"twitter-tweet\\\"\\u003E\\u003Cp\\u003ECool! \\u201C\\u003Ca href=\\\"https:\/\/twitter.com\/tw1tt3rart\\\"\\u003E@tw1tt3rart\\u003C\/a\\u003E: \\u003Ca href=\\\"https:\/\/twitter.com\/hashtag\/TWITTERART?src=hash\\\"\\u003E#TWITTERART\\u003C\/a\\u003E \\u2571\\u2571\\u2571\\u2571\\u2571\\u2571\\u2571\\u2571 \\u2571\\u2571\\u256D\\u2501\\u2501\\u2501\\u2501\\u256E\\u2571\\u2571\\u256D\\u2501\\u2501\\u2501\\u2501\\u256E \\u2571\\u2571\\u2503\\u2587\\u2506\\u2506\\u2587\\u2503\\u2571\\u256D\\u252B\\u24E6\\u24D4\\u24D4\\u24DA\\u2503 \\u2571\\u2571\\u2503\\u25BD\\u25BD\\u25BD\\u25BD\\u2503\\u2501\\u256F\\u2503\\u2661\\u24D4\\u24DD\\u24D3\\u2503 \\u2571\\u256D\\u252B\\u25B3\\u25B3\\u25B3\\u25B3\\u2523\\u256E\\u2571\\u2570\\u2501\\u2501\\u2501\\u2501\\u256F \\u2571\\u2503\\u2503\\u2506\\u2506\\u2506\\u2506\\u2503\\u2503\\u2571\\u2571\\u2571\\u2571\\u2571\\u2571 \\u2571\\u2517\\u252B\\u2506\\u250F\\u2513\\u2506\\u2523\\u251B\\u2571\\u2571\\u2571\\u2571\\u2571\\u201D\\u003C\/p\\u003E— Twitter (@twitter) \\u003Ca href=\\\"https:\/\/twitter.com\/twitter\/status\/99530515043983360\\\"\\u003EAugust 5, 2011\\u003C\/a\\u003E\\u003C\/blockquote\\u003E\\n\\u003Cscript async src=\\\"\/\/platform.twitter.com\/widgets.js\\\" charset=\\\"utf-8\\\"\\u003E\\u003C\/script\\u003E\",\n\tWidth: 550,\n}\ntest(TestOEmbed): fix test to make it passpackage anaconda_test\n\nimport (\n\t\"net\/url\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/ChimeraCoder\/anaconda\"\n)\n\nfunc TestOEmbed(t *testing.T) {\n\t\/\/ It is the only one that can be tested without auth\n\tapi := anaconda.NewTwitterApi(\"\", \"\")\n\to, err := api.GetOEmbed(url.Values{\"id\": []string{\"99530515043983360\"}})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif !reflect.DeepEqual(o, expectedOEmbed) {\n\t\tt.Errorf(\"Actual OEmbed differs expected:\\n%+v\\n Got: \\n%+v\\n\", expectedOEmbed, o)\n\t}\n}\n\nvar expectedOEmbed anaconda.OEmbed = anaconda.OEmbed{\n\tCache_age: \"3153600000\",\n\tUrl: \"https:\/\/twitter.com\/twitter\/statuses\/99530515043983360\",\n\tHeight: 0,\n\tProvider_url: \"https:\/\/twitter.com\",\n\tProvider_name: \"Twitter\",\n\tAuthor_name: \"Twitter\",\n\tVersion: \"1.0\",\n\tAuthor_url: \"https:\/\/twitter.com\/twitter\",\n\tType: \"rich\",\n\tHtml: `

Cool! “@tw1tt3rart<\/a>: #TWITTERART<\/a> ╱╱╱╱╱╱╱╱ ╱╱╭━━━━╮╱╱╭━━━━╮ ╱╱┃▇┆┆▇┃╱╭┫ⓦⓔⓔⓚ┃ ╱╱┃▽▽▽▽┃━╯┃♡ⓔⓝⓓ┃ ╱╭┫△△△△┣╮╱╰━━━━╯ ╱┃┃┆┆┆┆┃┃╱╱╱╱╱╱ ╱┗┫┆┏┓┆┣┛╱╱╱╱╱”<\/p>— Twitter (@twitter) August 5, 2011<\/a><\/blockquote>\n