repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
go-telegram-bot-api/telegram-bot-api
bot.go
KickChatMember
func (bot *BotAPI) KickChatMember(config KickChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.UntilDate != 0 { v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) } bot.debugLog("kickChatMember", v, nil) return bot.MakeRequest("kickChatMember", v) }
go
func (bot *BotAPI) KickChatMember(config KickChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.UntilDate != 0 { v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) } bot.debugLog("kickChatMember", v, nil) return bot.MakeRequest("kickChatMember", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "KickChatMember", "(", "config", "KickChatMemberConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "==", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n\n", "if", "config", ".", "UntilDate", "!=", "0", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "UntilDate", ",", "10", ")", ")", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// KickChatMember kicks a user from a chat. Note that this only will work // in supergroups, and requires the bot to be an admin. Also note they // will be unable to rejoin until they are unbanned.
[ "KickChatMember", "kicks", "a", "user", "from", "a", "chat", ".", "Note", "that", "this", "only", "will", "work", "in", "supergroups", "and", "requires", "the", "bot", "to", "be", "an", "admin", ".", "Also", "note", "they", "will", "be", "unable", "to", "rejoin", "until", "they", "are", "unbanned", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L585-L602
train
go-telegram-bot-api/telegram-bot-api
bot.go
LeaveChat
func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } bot.debugLog("leaveChat", v, nil) return bot.MakeRequest("leaveChat", v) }
go
func (bot *BotAPI) LeaveChat(config ChatConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } bot.debugLog("leaveChat", v, nil) return bot.MakeRequest("leaveChat", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "LeaveChat", "(", "config", "ChatConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "==", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// LeaveChat makes the bot leave the chat.
[ "LeaveChat", "makes", "the", "bot", "leave", "the", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L605-L617
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetChat
func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChat", v) if err != nil { return Chat{}, err } var chat Chat err = json.Unmarshal(resp.Result, &chat) bot.debugLog("getChat", v, chat) return chat, err }
go
func (bot *BotAPI) GetChat(config ChatConfig) (Chat, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChat", v) if err != nil { return Chat{}, err } var chat Chat err = json.Unmarshal(resp.Result, &chat) bot.debugLog("getChat", v, chat) return chat, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetChat", "(", "config", "ChatConfig", ")", "(", "Chat", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "==", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Chat", "{", "}", ",", "err", "\n", "}", "\n\n", "var", "chat", "Chat", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "chat", ")", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "chat", ")", "\n\n", "return", "chat", ",", "err", "\n", "}" ]
// GetChat gets information about a chat.
[ "GetChat", "gets", "information", "about", "a", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L620-L640
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetChatAdministrators
func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChatAdministrators", v) if err != nil { return []ChatMember{}, err } var members []ChatMember err = json.Unmarshal(resp.Result, &members) bot.debugLog("getChatAdministrators", v, members) return members, err }
go
func (bot *BotAPI) GetChatAdministrators(config ChatConfig) ([]ChatMember, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChatAdministrators", v) if err != nil { return []ChatMember{}, err } var members []ChatMember err = json.Unmarshal(resp.Result, &members) bot.debugLog("getChatAdministrators", v, members) return members, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetChatAdministrators", "(", "config", "ChatConfig", ")", "(", "[", "]", "ChatMember", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "==", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "ChatMember", "{", "}", ",", "err", "\n", "}", "\n\n", "var", "members", "[", "]", "ChatMember", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "members", ")", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "members", ")", "\n\n", "return", "members", ",", "err", "\n", "}" ]
// GetChatAdministrators gets a list of administrators in the chat. // // If none have been appointed, only the creator will be returned. // Bots are not shown, even if they are an administrator.
[ "GetChatAdministrators", "gets", "a", "list", "of", "administrators", "in", "the", "chat", ".", "If", "none", "have", "been", "appointed", "only", "the", "creator", "will", "be", "returned", ".", "Bots", "are", "not", "shown", "even", "if", "they", "are", "an", "administrator", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L646-L666
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetChatMembersCount
func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChatMembersCount", v) if err != nil { return -1, err } var count int err = json.Unmarshal(resp.Result, &count) bot.debugLog("getChatMembersCount", v, count) return count, err }
go
func (bot *BotAPI) GetChatMembersCount(config ChatConfig) (int, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("getChatMembersCount", v) if err != nil { return -1, err } var count int err = json.Unmarshal(resp.Result, &count) bot.debugLog("getChatMembersCount", v, count) return count, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetChatMembersCount", "(", "config", "ChatConfig", ")", "(", "int", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "==", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "var", "count", "int", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "count", ")", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "count", ")", "\n\n", "return", "count", ",", "err", "\n", "}" ]
// GetChatMembersCount gets the number of users in a chat.
[ "GetChatMembersCount", "gets", "the", "number", "of", "users", "in", "a", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L669-L689
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetChatMember
func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } v.Add("user_id", strconv.Itoa(config.UserID)) resp, err := bot.MakeRequest("getChatMember", v) if err != nil { return ChatMember{}, err } var member ChatMember err = json.Unmarshal(resp.Result, &member) bot.debugLog("getChatMember", v, member) return member, err }
go
func (bot *BotAPI) GetChatMember(config ChatConfigWithUser) (ChatMember, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } v.Add("user_id", strconv.Itoa(config.UserID)) resp, err := bot.MakeRequest("getChatMember", v) if err != nil { return ChatMember{}, err } var member ChatMember err = json.Unmarshal(resp.Result, &member) bot.debugLog("getChatMember", v, member) return member, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetChatMember", "(", "config", "ChatConfigWithUser", ")", "(", "ChatMember", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "==", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ChatMember", "{", "}", ",", "err", "\n", "}", "\n\n", "var", "member", "ChatMember", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "member", ")", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "member", ")", "\n\n", "return", "member", ",", "err", "\n", "}" ]
// GetChatMember gets a specific chat member.
[ "GetChatMember", "gets", "a", "specific", "chat", "member", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L692-L713
train
go-telegram-bot-api/telegram-bot-api
bot.go
UnbanChatMember
func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) bot.debugLog("unbanChatMember", v, nil) return bot.MakeRequest("unbanChatMember", v) }
go
func (bot *BotAPI) UnbanChatMember(config ChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) bot.debugLog("unbanChatMember", v, nil) return bot.MakeRequest("unbanChatMember", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "UnbanChatMember", "(", "config", "ChatMemberConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "else", "if", "config", ".", "ChannelUsername", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ChannelUsername", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// UnbanChatMember unbans a user from a chat. Note that this only will work // in supergroups and channels, and requires the bot to be an admin.
[ "UnbanChatMember", "unbans", "a", "user", "from", "a", "chat", ".", "Note", "that", "this", "only", "will", "work", "in", "supergroups", "and", "channels", "and", "requires", "the", "bot", "to", "be", "an", "admin", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L717-L732
train
go-telegram-bot-api/telegram-bot-api
bot.go
RestrictChatMember
func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.CanSendMessages != nil { v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages)) } if config.CanSendMediaMessages != nil { v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages)) } if config.CanSendOtherMessages != nil { v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages)) } if config.CanAddWebPagePreviews != nil { v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews)) } if config.UntilDate != 0 { v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) } bot.debugLog("restrictChatMember", v, nil) return bot.MakeRequest("restrictChatMember", v) }
go
func (bot *BotAPI) RestrictChatMember(config RestrictChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.CanSendMessages != nil { v.Add("can_send_messages", strconv.FormatBool(*config.CanSendMessages)) } if config.CanSendMediaMessages != nil { v.Add("can_send_media_messages", strconv.FormatBool(*config.CanSendMediaMessages)) } if config.CanSendOtherMessages != nil { v.Add("can_send_other_messages", strconv.FormatBool(*config.CanSendOtherMessages)) } if config.CanAddWebPagePreviews != nil { v.Add("can_add_web_page_previews", strconv.FormatBool(*config.CanAddWebPagePreviews)) } if config.UntilDate != 0 { v.Add("until_date", strconv.FormatInt(config.UntilDate, 10)) } bot.debugLog("restrictChatMember", v, nil) return bot.MakeRequest("restrictChatMember", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "RestrictChatMember", "(", "config", "RestrictChatMemberConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "else", "if", "config", ".", "ChannelUsername", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ChannelUsername", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n\n", "if", "config", ".", "CanSendMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanSendMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanSendMediaMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanSendMediaMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanSendOtherMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanSendOtherMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanAddWebPagePreviews", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanAddWebPagePreviews", ")", ")", "\n", "}", "\n", "if", "config", ".", "UntilDate", "!=", "0", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "UntilDate", ",", "10", ")", ")", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// RestrictChatMember to restrict a user in a supergroup. The bot must be an //administrator in the supergroup for this to work and must have the //appropriate admin rights. Pass True for all boolean parameters to lift //restrictions from a user. Returns True on success.
[ "RestrictChatMember", "to", "restrict", "a", "user", "in", "a", "supergroup", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "supergroup", "for", "this", "to", "work", "and", "must", "have", "the", "appropriate", "admin", "rights", ".", "Pass", "True", "for", "all", "boolean", "parameters", "to", "lift", "restrictions", "from", "a", "user", ".", "Returns", "True", "on", "success", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L738-L769
train
go-telegram-bot-api/telegram-bot-api
bot.go
PromoteChatMember
func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.CanChangeInfo != nil { v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo)) } if config.CanPostMessages != nil { v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages)) } if config.CanEditMessages != nil { v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages)) } if config.CanDeleteMessages != nil { v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages)) } if config.CanInviteUsers != nil { v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers)) } if config.CanRestrictMembers != nil { v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers)) } if config.CanPinMessages != nil { v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages)) } if config.CanPromoteMembers != nil { v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers)) } bot.debugLog("promoteChatMember", v, nil) return bot.MakeRequest("promoteChatMember", v) }
go
func (bot *BotAPI) PromoteChatMember(config PromoteChatMemberConfig) (APIResponse, error) { v := url.Values{} if config.SuperGroupUsername != "" { v.Add("chat_id", config.SuperGroupUsername) } else if config.ChannelUsername != "" { v.Add("chat_id", config.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } v.Add("user_id", strconv.Itoa(config.UserID)) if config.CanChangeInfo != nil { v.Add("can_change_info", strconv.FormatBool(*config.CanChangeInfo)) } if config.CanPostMessages != nil { v.Add("can_post_messages", strconv.FormatBool(*config.CanPostMessages)) } if config.CanEditMessages != nil { v.Add("can_edit_messages", strconv.FormatBool(*config.CanEditMessages)) } if config.CanDeleteMessages != nil { v.Add("can_delete_messages", strconv.FormatBool(*config.CanDeleteMessages)) } if config.CanInviteUsers != nil { v.Add("can_invite_users", strconv.FormatBool(*config.CanInviteUsers)) } if config.CanRestrictMembers != nil { v.Add("can_restrict_members", strconv.FormatBool(*config.CanRestrictMembers)) } if config.CanPinMessages != nil { v.Add("can_pin_messages", strconv.FormatBool(*config.CanPinMessages)) } if config.CanPromoteMembers != nil { v.Add("can_promote_members", strconv.FormatBool(*config.CanPromoteMembers)) } bot.debugLog("promoteChatMember", v, nil) return bot.MakeRequest("promoteChatMember", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "PromoteChatMember", "(", "config", "PromoteChatMemberConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "else", "if", "config", ".", "ChannelUsername", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ChannelUsername", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "UserID", ")", ")", "\n\n", "if", "config", ".", "CanChangeInfo", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanChangeInfo", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanPostMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanPostMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanEditMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanEditMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanDeleteMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanDeleteMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanInviteUsers", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanInviteUsers", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanRestrictMembers", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanRestrictMembers", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanPinMessages", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanPinMessages", ")", ")", "\n", "}", "\n", "if", "config", ".", "CanPromoteMembers", "!=", "nil", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "*", "config", ".", "CanPromoteMembers", ")", ")", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// PromoteChatMember add admin rights to user
[ "PromoteChatMember", "add", "admin", "rights", "to", "user" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L772-L812
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetGameHighScores
func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) { v, _ := config.values() resp, err := bot.MakeRequest(config.method(), v) if err != nil { return []GameHighScore{}, err } var highScores []GameHighScore err = json.Unmarshal(resp.Result, &highScores) return highScores, err }
go
func (bot *BotAPI) GetGameHighScores(config GetGameHighScoresConfig) ([]GameHighScore, error) { v, _ := config.values() resp, err := bot.MakeRequest(config.method(), v) if err != nil { return []GameHighScore{}, err } var highScores []GameHighScore err = json.Unmarshal(resp.Result, &highScores) return highScores, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetGameHighScores", "(", "config", "GetGameHighScoresConfig", ")", "(", "[", "]", "GameHighScore", ",", "error", ")", "{", "v", ",", "_", ":=", "config", ".", "values", "(", ")", "\n\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "GameHighScore", "{", "}", ",", "err", "\n", "}", "\n\n", "var", "highScores", "[", "]", "GameHighScore", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "highScores", ")", "\n\n", "return", "highScores", ",", "err", "\n", "}" ]
// GetGameHighScores allows you to get the high scores for a game.
[ "GetGameHighScores", "allows", "you", "to", "get", "the", "high", "scores", "for", "a", "game", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L815-L827
train
go-telegram-bot-api/telegram-bot-api
bot.go
AnswerShippingQuery
func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) { v := url.Values{} v.Add("shipping_query_id", config.ShippingQueryID) v.Add("ok", strconv.FormatBool(config.OK)) if config.OK == true { data, err := json.Marshal(config.ShippingOptions) if err != nil { return APIResponse{}, err } v.Add("shipping_options", string(data)) } else { v.Add("error_message", config.ErrorMessage) } bot.debugLog("answerShippingQuery", v, nil) return bot.MakeRequest("answerShippingQuery", v) }
go
func (bot *BotAPI) AnswerShippingQuery(config ShippingConfig) (APIResponse, error) { v := url.Values{} v.Add("shipping_query_id", config.ShippingQueryID) v.Add("ok", strconv.FormatBool(config.OK)) if config.OK == true { data, err := json.Marshal(config.ShippingOptions) if err != nil { return APIResponse{}, err } v.Add("shipping_options", string(data)) } else { v.Add("error_message", config.ErrorMessage) } bot.debugLog("answerShippingQuery", v, nil) return bot.MakeRequest("answerShippingQuery", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "AnswerShippingQuery", "(", "config", "ShippingConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ShippingQueryID", ")", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "config", ".", "OK", ")", ")", "\n", "if", "config", ".", "OK", "==", "true", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "config", ".", "ShippingOptions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "string", "(", "data", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ErrorMessage", ")", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// AnswerShippingQuery allows you to reply to Update with shipping_query parameter.
[ "AnswerShippingQuery", "allows", "you", "to", "reply", "to", "Update", "with", "shipping_query", "parameter", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L830-L848
train
go-telegram-bot-api/telegram-bot-api
bot.go
AnswerPreCheckoutQuery
func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) { v := url.Values{} v.Add("pre_checkout_query_id", config.PreCheckoutQueryID) v.Add("ok", strconv.FormatBool(config.OK)) if config.OK != true { v.Add("error", config.ErrorMessage) } bot.debugLog("answerPreCheckoutQuery", v, nil) return bot.MakeRequest("answerPreCheckoutQuery", v) }
go
func (bot *BotAPI) AnswerPreCheckoutQuery(config PreCheckoutConfig) (APIResponse, error) { v := url.Values{} v.Add("pre_checkout_query_id", config.PreCheckoutQueryID) v.Add("ok", strconv.FormatBool(config.OK)) if config.OK != true { v.Add("error", config.ErrorMessage) } bot.debugLog("answerPreCheckoutQuery", v, nil) return bot.MakeRequest("answerPreCheckoutQuery", v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "AnswerPreCheckoutQuery", "(", "config", "PreCheckoutConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "PreCheckoutQueryID", ")", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "config", ".", "OK", ")", ")", "\n", "if", "config", ".", "OK", "!=", "true", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ErrorMessage", ")", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "\"", "\"", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "}" ]
// AnswerPreCheckoutQuery allows you to reply to Update with pre_checkout_query.
[ "AnswerPreCheckoutQuery", "allows", "you", "to", "reply", "to", "Update", "with", "pre_checkout_query", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L851-L863
train
go-telegram-bot-api/telegram-bot-api
bot.go
DeleteMessage
func (bot *BotAPI) DeleteMessage(config DeleteMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) DeleteMessage(config DeleteMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "DeleteMessage", "(", "config", "DeleteMessageConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// DeleteMessage deletes a message in a chat
[ "DeleteMessage", "deletes", "a", "message", "in", "a", "chat" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L866-L875
train
go-telegram-bot-api/telegram-bot-api
bot.go
GetInviteLink
func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("exportChatInviteLink", v) if err != nil { return "", err } var inviteLink string err = json.Unmarshal(resp.Result, &inviteLink) return inviteLink, err }
go
func (bot *BotAPI) GetInviteLink(config ChatConfig) (string, error) { v := url.Values{} if config.SuperGroupUsername == "" { v.Add("chat_id", strconv.FormatInt(config.ChatID, 10)) } else { v.Add("chat_id", config.SuperGroupUsername) } resp, err := bot.MakeRequest("exportChatInviteLink", v) if err != nil { return "", err } var inviteLink string err = json.Unmarshal(resp.Result, &inviteLink) return inviteLink, err }
[ "func", "(", "bot", "*", "BotAPI", ")", "GetInviteLink", "(", "config", "ChatConfig", ")", "(", "string", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n\n", "if", "config", ".", "SuperGroupUsername", "==", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "SuperGroupUsername", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "bot", ".", "MakeRequest", "(", "\"", "\"", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "var", "inviteLink", "string", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ".", "Result", ",", "&", "inviteLink", ")", "\n\n", "return", "inviteLink", ",", "err", "\n", "}" ]
// GetInviteLink get InviteLink for a chat
[ "GetInviteLink", "get", "InviteLink", "for", "a", "chat" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L878-L896
train
go-telegram-bot-api/telegram-bot-api
bot.go
PinChatMessage
func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) PinChatMessage(config PinChatMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "PinChatMessage", "(", "config", "PinChatMessageConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// PinChatMessage pin message in supergroup
[ "PinChatMessage", "pin", "message", "in", "supergroup" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L899-L908
train
go-telegram-bot-api/telegram-bot-api
bot.go
UnpinChatMessage
func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) UnpinChatMessage(config UnpinChatMessageConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "UnpinChatMessage", "(", "config", "UnpinChatMessageConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// UnpinChatMessage unpin message in supergroup
[ "UnpinChatMessage", "unpin", "message", "in", "supergroup" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L911-L920
train
go-telegram-bot-api/telegram-bot-api
bot.go
SetChatTitle
func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) SetChatTitle(config SetChatTitleConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "SetChatTitle", "(", "config", "SetChatTitleConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// SetChatTitle change title of chat.
[ "SetChatTitle", "change", "title", "of", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L923-L932
train
go-telegram-bot-api/telegram-bot-api
bot.go
SetChatDescription
func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) SetChatDescription(config SetChatDescriptionConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "SetChatDescription", "(", "config", "SetChatDescriptionConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// SetChatDescription change description of chat.
[ "SetChatDescription", "change", "description", "of", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L935-L944
train
go-telegram-bot-api/telegram-bot-api
bot.go
SetChatPhoto
func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) { params, err := config.params() if err != nil { return APIResponse{}, err } file := config.getFile() return bot.UploadFile(config.method(), params, config.name(), file) }
go
func (bot *BotAPI) SetChatPhoto(config SetChatPhotoConfig) (APIResponse, error) { params, err := config.params() if err != nil { return APIResponse{}, err } file := config.getFile() return bot.UploadFile(config.method(), params, config.name(), file) }
[ "func", "(", "bot", "*", "BotAPI", ")", "SetChatPhoto", "(", "config", "SetChatPhotoConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "params", ",", "err", ":=", "config", ".", "params", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n\n", "file", ":=", "config", ".", "getFile", "(", ")", "\n\n", "return", "bot", ".", "UploadFile", "(", "config", ".", "method", "(", ")", ",", "params", ",", "config", ".", "name", "(", ")", ",", "file", ")", "\n", "}" ]
// SetChatPhoto change photo of chat.
[ "SetChatPhoto", "change", "photo", "of", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L947-L956
train
go-telegram-bot-api/telegram-bot-api
bot.go
DeleteChatPhoto
func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
go
func (bot *BotAPI) DeleteChatPhoto(config DeleteChatPhotoConfig) (APIResponse, error) { v, err := config.values() if err != nil { return APIResponse{}, err } bot.debugLog(config.method(), v, nil) return bot.MakeRequest(config.method(), v) }
[ "func", "(", "bot", "*", "BotAPI", ")", "DeleteChatPhoto", "(", "config", "DeleteChatPhotoConfig", ")", "(", "APIResponse", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "APIResponse", "{", "}", ",", "err", "\n", "}", "\n\n", "bot", ".", "debugLog", "(", "config", ".", "method", "(", ")", ",", "v", ",", "nil", ")", "\n\n", "return", "bot", ".", "MakeRequest", "(", "config", ".", "method", "(", ")", ",", "v", ")", "\n", "}" ]
// DeleteChatPhoto delete photo of chat.
[ "DeleteChatPhoto", "delete", "photo", "of", "chat", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/bot.go#L959-L968
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (chat *BaseChat) values() (url.Values, error) { v := url.Values{} if chat.ChannelUsername != "" { v.Add("chat_id", chat.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(chat.ChatID, 10)) } if chat.ReplyToMessageID != 0 { v.Add("reply_to_message_id", strconv.Itoa(chat.ReplyToMessageID)) } if chat.ReplyMarkup != nil { data, err := json.Marshal(chat.ReplyMarkup) if err != nil { return v, err } v.Add("reply_markup", string(data)) } v.Add("disable_notification", strconv.FormatBool(chat.DisableNotification)) return v, nil }
go
func (chat *BaseChat) values() (url.Values, error) { v := url.Values{} if chat.ChannelUsername != "" { v.Add("chat_id", chat.ChannelUsername) } else { v.Add("chat_id", strconv.FormatInt(chat.ChatID, 10)) } if chat.ReplyToMessageID != 0 { v.Add("reply_to_message_id", strconv.Itoa(chat.ReplyToMessageID)) } if chat.ReplyMarkup != nil { data, err := json.Marshal(chat.ReplyMarkup) if err != nil { return v, err } v.Add("reply_markup", string(data)) } v.Add("disable_notification", strconv.FormatBool(chat.DisableNotification)) return v, nil }
[ "func", "(", "chat", "*", "BaseChat", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ":=", "url", ".", "Values", "{", "}", "\n", "if", "chat", ".", "ChannelUsername", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "chat", ".", "ChannelUsername", ")", "\n", "}", "else", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "chat", ".", "ChatID", ",", "10", ")", ")", "\n", "}", "\n\n", "if", "chat", ".", "ReplyToMessageID", "!=", "0", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "chat", ".", "ReplyToMessageID", ")", ")", "\n", "}", "\n\n", "if", "chat", ".", "ReplyMarkup", "!=", "nil", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "chat", ".", "ReplyMarkup", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n\n", "v", ".", "Add", "(", "\"", "\"", ",", "string", "(", "data", ")", ")", "\n", "}", "\n\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "chat", ".", "DisableNotification", ")", ")", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns url.Values representation of BaseChat
[ "values", "returns", "url", ".", "Values", "representation", "of", "BaseChat" ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L75-L99
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config MessageConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("text", config.Text) v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview)) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } return v, nil }
go
func (config MessageConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("text", config.Text) v.Add("disable_web_page_preview", strconv.FormatBool(config.DisableWebPagePreview)) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } return v, nil }
[ "func", "(", "config", "MessageConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "Text", ")", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatBool", "(", "config", ".", "DisableWebPagePreview", ")", ")", "\n", "if", "config", ".", "ParseMode", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ParseMode", ")", "\n", "}", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of MessageConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "MessageConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L200-L212
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config ForwardConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("from_chat_id", strconv.FormatInt(config.FromChatID, 10)) v.Add("message_id", strconv.Itoa(config.MessageID)) return v, nil }
go
func (config ForwardConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("from_chat_id", strconv.FormatInt(config.FromChatID, 10)) v.Add("message_id", strconv.Itoa(config.MessageID)) return v, nil }
[ "func", "(", "config", "ForwardConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "config", ".", "FromChatID", ",", "10", ")", ")", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "MessageID", ")", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of ForwardConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "ForwardConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L228-L236
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config DocumentConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Caption != "" { v.Add("caption", config.Caption) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } } return v, nil }
go
func (config DocumentConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Caption != "" { v.Add("caption", config.Caption) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } } return v, nil }
[ "func", "(", "config", "DocumentConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n\n", "v", ".", "Add", "(", "config", ".", "name", "(", ")", ",", "config", ".", "FileID", ")", "\n", "if", "config", ".", "Caption", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "Caption", ")", "\n", "if", "config", ".", "ParseMode", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ParseMode", ")", "\n", "}", "\n", "}", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of DocumentConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "DocumentConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L372-L387
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config StickerConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) return v, nil }
go
func (config StickerConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) return v, nil }
[ "func", "(", "config", "StickerConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n\n", "v", ".", "Add", "(", "config", ".", "name", "(", ")", ",", "config", ".", "FileID", ")", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of StickerConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "StickerConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L419-L428
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config VideoConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Duration != 0 { v.Add("duration", strconv.Itoa(config.Duration)) } if config.Caption != "" { v.Add("caption", config.Caption) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } } return v, nil }
go
func (config VideoConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Duration != 0 { v.Add("duration", strconv.Itoa(config.Duration)) } if config.Caption != "" { v.Add("caption", config.Caption) if config.ParseMode != "" { v.Add("parse_mode", config.ParseMode) } } return v, nil }
[ "func", "(", "config", "VideoConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n\n", "v", ".", "Add", "(", "config", ".", "name", "(", ")", ",", "config", ".", "FileID", ")", "\n", "if", "config", ".", "Duration", "!=", "0", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Duration", ")", ")", "\n", "}", "\n", "if", "config", ".", "Caption", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "Caption", ")", "\n", "if", "config", ".", "ParseMode", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "ParseMode", ")", "\n", "}", "\n", "}", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of VideoConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "VideoConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L456-L474
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config VideoNoteConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Duration != 0 { v.Add("duration", strconv.Itoa(config.Duration)) } // Telegram API seems to have a bug, if no length is provided or it is 0, it will send an error response if config.Length != 0 { v.Add("length", strconv.Itoa(config.Length)) } return v, nil }
go
func (config VideoNoteConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add(config.name(), config.FileID) if config.Duration != 0 { v.Add("duration", strconv.Itoa(config.Duration)) } // Telegram API seems to have a bug, if no length is provided or it is 0, it will send an error response if config.Length != 0 { v.Add("length", strconv.Itoa(config.Length)) } return v, nil }
[ "func", "(", "config", "VideoNoteConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n\n", "v", ".", "Add", "(", "config", ".", "name", "(", ")", ",", "config", ".", "FileID", ")", "\n", "if", "config", ".", "Duration", "!=", "0", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Duration", ")", ")", "\n", "}", "\n\n", "// Telegram API seems to have a bug, if no length is provided or it is 0, it will send an error response", "if", "config", ".", "Length", "!=", "0", "{", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "config", ".", "Length", ")", ")", "\n", "}", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of VideoNoteConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "VideoNoteConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L561-L578
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config LocationConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64)) v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64)) return v, nil }
go
func (config LocationConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64)) v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64)) return v, nil }
[ "func", "(", "config", "LocationConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatFloat", "(", "config", ".", "Latitude", ",", "'f'", ",", "6", ",", "64", ")", ")", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "strconv", ".", "FormatFloat", "(", "config", ".", "Longitude", ",", "'f'", ",", "6", ",", "64", ")", ")", "\n\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of LocationConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "LocationConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L694-L704
train
go-telegram-bot-api/telegram-bot-api
configs.go
values
func (config ChatActionConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("action", config.Action) return v, nil }
go
func (config ChatActionConfig) values() (url.Values, error) { v, err := config.BaseChat.values() if err != nil { return v, err } v.Add("action", config.Action) return v, nil }
[ "func", "(", "config", "ChatActionConfig", ")", "values", "(", ")", "(", "url", ".", "Values", ",", "error", ")", "{", "v", ",", "err", ":=", "config", ".", "BaseChat", ".", "values", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "v", ",", "err", "\n", "}", "\n", "v", ".", "Add", "(", "\"", "\"", ",", "config", ".", "Action", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// values returns a url.Values representation of ChatActionConfig.
[ "values", "returns", "a", "url", ".", "Values", "representation", "of", "ChatActionConfig", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/configs.go#L862-L869
train
go-telegram-bot-api/telegram-bot-api
log.go
SetLogger
func SetLogger(logger BotLogger) error { if logger == nil { return errors.New("logger is nil") } log = logger return nil }
go
func SetLogger(logger BotLogger) error { if logger == nil { return errors.New("logger is nil") } log = logger return nil }
[ "func", "SetLogger", "(", "logger", "BotLogger", ")", "error", "{", "if", "logger", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "log", "=", "logger", "\n", "return", "nil", "\n", "}" ]
// SetLogger specifies the logger that the package should use.
[ "SetLogger", "specifies", "the", "logger", "that", "the", "package", "should", "use", "." ]
87e7035a900c7cb1fd896e5f33b461c96c3ac31e
https://github.com/go-telegram-bot-api/telegram-bot-api/blob/87e7035a900c7cb1fd896e5f33b461c96c3ac31e/log.go#L21-L27
train
nsf/termbox-go
termbox_windows.go
prepare_diff_messages
func prepare_diff_messages() { // clear buffers diffbuf = diffbuf[:0] charbuf = charbuf[:0] var diff diff_msg gbeg := 0 for y := 0; y < front_buffer.height; y++ { same := true line_offset := y * front_buffer.width for x := 0; x < front_buffer.width; x++ { cell_offset := line_offset + x back := &back_buffer.cells[cell_offset] front := &front_buffer.cells[cell_offset] if *back != *front { same = false break } } if same && diff.lines > 0 { diffbuf = append(diffbuf, diff) diff = diff_msg{} } if !same { beg := len(charbuf) end := beg + append_diff_line(y) if diff.lines == 0 { diff.pos = short(y) gbeg = beg } diff.lines++ diff.chars = charbuf[gbeg:end] } } if diff.lines > 0 { diffbuf = append(diffbuf, diff) diff = diff_msg{} } }
go
func prepare_diff_messages() { // clear buffers diffbuf = diffbuf[:0] charbuf = charbuf[:0] var diff diff_msg gbeg := 0 for y := 0; y < front_buffer.height; y++ { same := true line_offset := y * front_buffer.width for x := 0; x < front_buffer.width; x++ { cell_offset := line_offset + x back := &back_buffer.cells[cell_offset] front := &front_buffer.cells[cell_offset] if *back != *front { same = false break } } if same && diff.lines > 0 { diffbuf = append(diffbuf, diff) diff = diff_msg{} } if !same { beg := len(charbuf) end := beg + append_diff_line(y) if diff.lines == 0 { diff.pos = short(y) gbeg = beg } diff.lines++ diff.chars = charbuf[gbeg:end] } } if diff.lines > 0 { diffbuf = append(diffbuf, diff) diff = diff_msg{} } }
[ "func", "prepare_diff_messages", "(", ")", "{", "// clear buffers", "diffbuf", "=", "diffbuf", "[", ":", "0", "]", "\n", "charbuf", "=", "charbuf", "[", ":", "0", "]", "\n\n", "var", "diff", "diff_msg", "\n", "gbeg", ":=", "0", "\n", "for", "y", ":=", "0", ";", "y", "<", "front_buffer", ".", "height", ";", "y", "++", "{", "same", ":=", "true", "\n", "line_offset", ":=", "y", "*", "front_buffer", ".", "width", "\n", "for", "x", ":=", "0", ";", "x", "<", "front_buffer", ".", "width", ";", "x", "++", "{", "cell_offset", ":=", "line_offset", "+", "x", "\n", "back", ":=", "&", "back_buffer", ".", "cells", "[", "cell_offset", "]", "\n", "front", ":=", "&", "front_buffer", ".", "cells", "[", "cell_offset", "]", "\n", "if", "*", "back", "!=", "*", "front", "{", "same", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "same", "&&", "diff", ".", "lines", ">", "0", "{", "diffbuf", "=", "append", "(", "diffbuf", ",", "diff", ")", "\n", "diff", "=", "diff_msg", "{", "}", "\n", "}", "\n", "if", "!", "same", "{", "beg", ":=", "len", "(", "charbuf", ")", "\n", "end", ":=", "beg", "+", "append_diff_line", "(", "y", ")", "\n", "if", "diff", ".", "lines", "==", "0", "{", "diff", ".", "pos", "=", "short", "(", "y", ")", "\n", "gbeg", "=", "beg", "\n", "}", "\n", "diff", ".", "lines", "++", "\n", "diff", ".", "chars", "=", "charbuf", "[", "gbeg", ":", "end", "]", "\n", "}", "\n", "}", "\n", "if", "diff", ".", "lines", ">", "0", "{", "diffbuf", "=", "append", "(", "diffbuf", ",", "diff", ")", "\n", "diff", "=", "diff_msg", "{", "}", "\n", "}", "\n", "}" ]
// compares 'back_buffer' with 'front_buffer' and prepares all changes in the form of // 'diff_msg's in the 'diff_buf'
[ "compares", "back_buffer", "with", "front_buffer", "and", "prepares", "all", "changes", "in", "the", "form", "of", "diff_msg", "s", "in", "the", "diff_buf" ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/termbox_windows.go#L577-L615
train
nsf/termbox-go
api_windows.go
SetCell
func SetCell(x, y int, ch rune, fg, bg Attribute) { if x < 0 || x >= back_buffer.width { return } if y < 0 || y >= back_buffer.height { return } back_buffer.cells[y*back_buffer.width+x] = Cell{ch, fg, bg} }
go
func SetCell(x, y int, ch rune, fg, bg Attribute) { if x < 0 || x >= back_buffer.width { return } if y < 0 || y >= back_buffer.height { return } back_buffer.cells[y*back_buffer.width+x] = Cell{ch, fg, bg} }
[ "func", "SetCell", "(", "x", ",", "y", "int", ",", "ch", "rune", ",", "fg", ",", "bg", "Attribute", ")", "{", "if", "x", "<", "0", "||", "x", ">=", "back_buffer", ".", "width", "{", "return", "\n", "}", "\n", "if", "y", "<", "0", "||", "y", ">=", "back_buffer", ".", "height", "{", "return", "\n", "}", "\n\n", "back_buffer", ".", "cells", "[", "y", "*", "back_buffer", ".", "width", "+", "x", "]", "=", "Cell", "{", "ch", ",", "fg", ",", "bg", "}", "\n", "}" ]
// Changes cell's parameters in the internal back buffer at the specified // position.
[ "Changes", "cell", "s", "parameters", "in", "the", "internal", "back", "buffer", "at", "the", "specified", "position", "." ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/api_windows.go#L154-L163
train
nsf/termbox-go
_demos/editbox.go
Draw
func (eb *EditBox) Draw(x, y, w, h int) { eb.AdjustVOffset(w) const coldef = termbox.ColorDefault fill(x, y, w, h, termbox.Cell{Ch: ' '}) t := eb.text lx := 0 tabstop := 0 for { rx := lx - eb.line_voffset if len(t) == 0 { break } if lx == tabstop { tabstop += tabstop_length } if rx >= w { termbox.SetCell(x+w-1, y, '→', coldef, coldef) break } r, size := utf8.DecodeRune(t) if r == '\t' { for ; lx < tabstop; lx++ { rx = lx - eb.line_voffset if rx >= w { goto next } if rx >= 0 { termbox.SetCell(x+rx, y, ' ', coldef, coldef) } } } else { if rx >= 0 { termbox.SetCell(x+rx, y, r, coldef, coldef) } lx += runewidth.RuneWidth(r) } next: t = t[size:] } if eb.line_voffset != 0 { termbox.SetCell(x, y, '←', coldef, coldef) } }
go
func (eb *EditBox) Draw(x, y, w, h int) { eb.AdjustVOffset(w) const coldef = termbox.ColorDefault fill(x, y, w, h, termbox.Cell{Ch: ' '}) t := eb.text lx := 0 tabstop := 0 for { rx := lx - eb.line_voffset if len(t) == 0 { break } if lx == tabstop { tabstop += tabstop_length } if rx >= w { termbox.SetCell(x+w-1, y, '→', coldef, coldef) break } r, size := utf8.DecodeRune(t) if r == '\t' { for ; lx < tabstop; lx++ { rx = lx - eb.line_voffset if rx >= w { goto next } if rx >= 0 { termbox.SetCell(x+rx, y, ' ', coldef, coldef) } } } else { if rx >= 0 { termbox.SetCell(x+rx, y, r, coldef, coldef) } lx += runewidth.RuneWidth(r) } next: t = t[size:] } if eb.line_voffset != 0 { termbox.SetCell(x, y, '←', coldef, coldef) } }
[ "func", "(", "eb", "*", "EditBox", ")", "Draw", "(", "x", ",", "y", ",", "w", ",", "h", "int", ")", "{", "eb", ".", "AdjustVOffset", "(", "w", ")", "\n\n", "const", "coldef", "=", "termbox", ".", "ColorDefault", "\n", "fill", "(", "x", ",", "y", ",", "w", ",", "h", ",", "termbox", ".", "Cell", "{", "Ch", ":", "' '", "}", ")", "\n\n", "t", ":=", "eb", ".", "text", "\n", "lx", ":=", "0", "\n", "tabstop", ":=", "0", "\n", "for", "{", "rx", ":=", "lx", "-", "eb", ".", "line_voffset", "\n", "if", "len", "(", "t", ")", "==", "0", "{", "break", "\n", "}", "\n\n", "if", "lx", "==", "tabstop", "{", "tabstop", "+=", "tabstop_length", "\n", "}", "\n\n", "if", "rx", ">=", "w", "{", "termbox", ".", "SetCell", "(", "x", "+", "w", "-", "1", ",", "y", ",", "'→',", "", "coldef", ",", "coldef", ")", "\n", "break", "\n", "}", "\n\n", "r", ",", "size", ":=", "utf8", ".", "DecodeRune", "(", "t", ")", "\n", "if", "r", "==", "'\\t'", "{", "for", ";", "lx", "<", "tabstop", ";", "lx", "++", "{", "rx", "=", "lx", "-", "eb", ".", "line_voffset", "\n", "if", "rx", ">=", "w", "{", "goto", "next", "\n", "}", "\n\n", "if", "rx", ">=", "0", "{", "termbox", ".", "SetCell", "(", "x", "+", "rx", ",", "y", ",", "' '", ",", "coldef", ",", "coldef", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "if", "rx", ">=", "0", "{", "termbox", ".", "SetCell", "(", "x", "+", "rx", ",", "y", ",", "r", ",", "coldef", ",", "coldef", ")", "\n", "}", "\n", "lx", "+=", "runewidth", ".", "RuneWidth", "(", "r", ")", "\n", "}", "\n", "next", ":", "t", "=", "t", "[", "size", ":", "]", "\n", "}", "\n\n", "if", "eb", ".", "line_voffset", "!=", "0", "{", "termbox", ".", "SetCell", "(", "x", ",", "y", ",", "'←', ", "c", "ldef, ", "c", "ldef)", "", "\n", "}", "\n", "}" ]
// Draws the EditBox in the given location, 'h' is not used at the moment
[ "Draws", "the", "EditBox", "in", "the", "given", "location", "h", "is", "not", "used", "at", "the", "moment" ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/_demos/editbox.go#L79-L129
train
nsf/termbox-go
_demos/editbox.go
AdjustVOffset
func (eb *EditBox) AdjustVOffset(width int) { ht := preferred_horizontal_threshold max_h_threshold := (width - 1) / 2 if ht > max_h_threshold { ht = max_h_threshold } threshold := width - 1 if eb.line_voffset != 0 { threshold = width - ht } if eb.cursor_voffset-eb.line_voffset >= threshold { eb.line_voffset = eb.cursor_voffset + (ht - width + 1) } if eb.line_voffset != 0 && eb.cursor_voffset-eb.line_voffset < ht { eb.line_voffset = eb.cursor_voffset - ht if eb.line_voffset < 0 { eb.line_voffset = 0 } } }
go
func (eb *EditBox) AdjustVOffset(width int) { ht := preferred_horizontal_threshold max_h_threshold := (width - 1) / 2 if ht > max_h_threshold { ht = max_h_threshold } threshold := width - 1 if eb.line_voffset != 0 { threshold = width - ht } if eb.cursor_voffset-eb.line_voffset >= threshold { eb.line_voffset = eb.cursor_voffset + (ht - width + 1) } if eb.line_voffset != 0 && eb.cursor_voffset-eb.line_voffset < ht { eb.line_voffset = eb.cursor_voffset - ht if eb.line_voffset < 0 { eb.line_voffset = 0 } } }
[ "func", "(", "eb", "*", "EditBox", ")", "AdjustVOffset", "(", "width", "int", ")", "{", "ht", ":=", "preferred_horizontal_threshold", "\n", "max_h_threshold", ":=", "(", "width", "-", "1", ")", "/", "2", "\n", "if", "ht", ">", "max_h_threshold", "{", "ht", "=", "max_h_threshold", "\n", "}", "\n\n", "threshold", ":=", "width", "-", "1", "\n", "if", "eb", ".", "line_voffset", "!=", "0", "{", "threshold", "=", "width", "-", "ht", "\n", "}", "\n", "if", "eb", ".", "cursor_voffset", "-", "eb", ".", "line_voffset", ">=", "threshold", "{", "eb", ".", "line_voffset", "=", "eb", ".", "cursor_voffset", "+", "(", "ht", "-", "width", "+", "1", ")", "\n", "}", "\n\n", "if", "eb", ".", "line_voffset", "!=", "0", "&&", "eb", ".", "cursor_voffset", "-", "eb", ".", "line_voffset", "<", "ht", "{", "eb", ".", "line_voffset", "=", "eb", ".", "cursor_voffset", "-", "ht", "\n", "if", "eb", ".", "line_voffset", "<", "0", "{", "eb", ".", "line_voffset", "=", "0", "\n", "}", "\n", "}", "\n", "}" ]
// Adjusts line visual offset to a proper value depending on width
[ "Adjusts", "line", "visual", "offset", "to", "a", "proper", "value", "depending", "on", "width" ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/_demos/editbox.go#L132-L153
train
nsf/termbox-go
api.go
PollEvent
func PollEvent() Event { // Constant governing macOS specific behavior. See https://github.com/nsf/termbox-go/issues/132 // This is an arbitrary delay which hopefully will be enough time for any lagging // partial escape sequences to come through. const esc_wait_delay = 100 * time.Millisecond var event Event var esc_wait_timer *time.Timer var esc_timeout <-chan time.Time // try to extract event from input buffer, return on success event.Type = EventKey status := extract_event(inbuf, &event, true) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } else if status == esc_wait { esc_wait_timer = time.NewTimer(esc_wait_delay) esc_timeout = esc_wait_timer.C } for { select { case ev := <-input_comm: if esc_wait_timer != nil { if !esc_wait_timer.Stop() { <-esc_wait_timer.C } esc_wait_timer = nil } if ev.err != nil { return Event{Type: EventError, Err: ev.err} } inbuf = append(inbuf, ev.data...) input_comm <- ev status := extract_event(inbuf, &event, true) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } else if status == esc_wait { esc_wait_timer = time.NewTimer(esc_wait_delay) esc_timeout = esc_wait_timer.C } case <-esc_timeout: esc_wait_timer = nil status := extract_event(inbuf, &event, false) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } case <-interrupt_comm: event.Type = EventInterrupt return event case <-sigwinch: event.Type = EventResize event.Width, event.Height = get_term_size(out.Fd()) return event } } }
go
func PollEvent() Event { // Constant governing macOS specific behavior. See https://github.com/nsf/termbox-go/issues/132 // This is an arbitrary delay which hopefully will be enough time for any lagging // partial escape sequences to come through. const esc_wait_delay = 100 * time.Millisecond var event Event var esc_wait_timer *time.Timer var esc_timeout <-chan time.Time // try to extract event from input buffer, return on success event.Type = EventKey status := extract_event(inbuf, &event, true) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } else if status == esc_wait { esc_wait_timer = time.NewTimer(esc_wait_delay) esc_timeout = esc_wait_timer.C } for { select { case ev := <-input_comm: if esc_wait_timer != nil { if !esc_wait_timer.Stop() { <-esc_wait_timer.C } esc_wait_timer = nil } if ev.err != nil { return Event{Type: EventError, Err: ev.err} } inbuf = append(inbuf, ev.data...) input_comm <- ev status := extract_event(inbuf, &event, true) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } else if status == esc_wait { esc_wait_timer = time.NewTimer(esc_wait_delay) esc_timeout = esc_wait_timer.C } case <-esc_timeout: esc_wait_timer = nil status := extract_event(inbuf, &event, false) if event.N != 0 { copy(inbuf, inbuf[event.N:]) inbuf = inbuf[:len(inbuf)-event.N] } if status == event_extracted { return event } case <-interrupt_comm: event.Type = EventInterrupt return event case <-sigwinch: event.Type = EventResize event.Width, event.Height = get_term_size(out.Fd()) return event } } }
[ "func", "PollEvent", "(", ")", "Event", "{", "// Constant governing macOS specific behavior. See https://github.com/nsf/termbox-go/issues/132", "// This is an arbitrary delay which hopefully will be enough time for any lagging", "// partial escape sequences to come through.", "const", "esc_wait_delay", "=", "100", "*", "time", ".", "Millisecond", "\n\n", "var", "event", "Event", "\n", "var", "esc_wait_timer", "*", "time", ".", "Timer", "\n", "var", "esc_timeout", "<-", "chan", "time", ".", "Time", "\n\n", "// try to extract event from input buffer, return on success", "event", ".", "Type", "=", "EventKey", "\n", "status", ":=", "extract_event", "(", "inbuf", ",", "&", "event", ",", "true", ")", "\n", "if", "event", ".", "N", "!=", "0", "{", "copy", "(", "inbuf", ",", "inbuf", "[", "event", ".", "N", ":", "]", ")", "\n", "inbuf", "=", "inbuf", "[", ":", "len", "(", "inbuf", ")", "-", "event", ".", "N", "]", "\n", "}", "\n", "if", "status", "==", "event_extracted", "{", "return", "event", "\n", "}", "else", "if", "status", "==", "esc_wait", "{", "esc_wait_timer", "=", "time", ".", "NewTimer", "(", "esc_wait_delay", ")", "\n", "esc_timeout", "=", "esc_wait_timer", ".", "C", "\n", "}", "\n\n", "for", "{", "select", "{", "case", "ev", ":=", "<-", "input_comm", ":", "if", "esc_wait_timer", "!=", "nil", "{", "if", "!", "esc_wait_timer", ".", "Stop", "(", ")", "{", "<-", "esc_wait_timer", ".", "C", "\n", "}", "\n", "esc_wait_timer", "=", "nil", "\n", "}", "\n\n", "if", "ev", ".", "err", "!=", "nil", "{", "return", "Event", "{", "Type", ":", "EventError", ",", "Err", ":", "ev", ".", "err", "}", "\n", "}", "\n\n", "inbuf", "=", "append", "(", "inbuf", ",", "ev", ".", "data", "...", ")", "\n", "input_comm", "<-", "ev", "\n", "status", ":=", "extract_event", "(", "inbuf", ",", "&", "event", ",", "true", ")", "\n", "if", "event", ".", "N", "!=", "0", "{", "copy", "(", "inbuf", ",", "inbuf", "[", "event", ".", "N", ":", "]", ")", "\n", "inbuf", "=", "inbuf", "[", ":", "len", "(", "inbuf", ")", "-", "event", ".", "N", "]", "\n", "}", "\n", "if", "status", "==", "event_extracted", "{", "return", "event", "\n", "}", "else", "if", "status", "==", "esc_wait", "{", "esc_wait_timer", "=", "time", ".", "NewTimer", "(", "esc_wait_delay", ")", "\n", "esc_timeout", "=", "esc_wait_timer", ".", "C", "\n", "}", "\n", "case", "<-", "esc_timeout", ":", "esc_wait_timer", "=", "nil", "\n\n", "status", ":=", "extract_event", "(", "inbuf", ",", "&", "event", ",", "false", ")", "\n", "if", "event", ".", "N", "!=", "0", "{", "copy", "(", "inbuf", ",", "inbuf", "[", "event", ".", "N", ":", "]", ")", "\n", "inbuf", "=", "inbuf", "[", ":", "len", "(", "inbuf", ")", "-", "event", ".", "N", "]", "\n", "}", "\n", "if", "status", "==", "event_extracted", "{", "return", "event", "\n", "}", "\n", "case", "<-", "interrupt_comm", ":", "event", ".", "Type", "=", "EventInterrupt", "\n", "return", "event", "\n\n", "case", "<-", "sigwinch", ":", "event", ".", "Type", "=", "EventResize", "\n", "event", ".", "Width", ",", "event", ".", "Height", "=", "get_term_size", "(", "out", ".", "Fd", "(", ")", ")", "\n", "return", "event", "\n", "}", "\n", "}", "\n", "}" ]
// Wait for an event and return it. This is a blocking function call.
[ "Wait", "for", "an", "event", "and", "return", "it", ".", "This", "is", "a", "blocking", "function", "call", "." ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/api.go#L314-L386
train
nsf/termbox-go
api.go
Clear
func Clear(fg, bg Attribute) error { foreground, background = fg, bg err := update_size_maybe() back_buffer.clear() return err }
go
func Clear(fg, bg Attribute) error { foreground, background = fg, bg err := update_size_maybe() back_buffer.clear() return err }
[ "func", "Clear", "(", "fg", ",", "bg", "Attribute", ")", "error", "{", "foreground", ",", "background", "=", "fg", ",", "bg", "\n", "err", ":=", "update_size_maybe", "(", ")", "\n", "back_buffer", ".", "clear", "(", ")", "\n", "return", "err", "\n", "}" ]
// Clears the internal back buffer.
[ "Clears", "the", "internal", "back", "buffer", "." ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/api.go#L397-L402
train
nsf/termbox-go
api.go
Sync
func Sync() error { front_buffer.clear() err := send_clear() if err != nil { return err } return Flush() }
go
func Sync() error { front_buffer.clear() err := send_clear() if err != nil { return err } return Flush() }
[ "func", "Sync", "(", ")", "error", "{", "front_buffer", ".", "clear", "(", ")", "\n", "err", ":=", "send_clear", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "Flush", "(", ")", "\n", "}" ]
// Sync comes handy when something causes desync between termbox's understanding // of a terminal buffer and the reality. Such as a third party process. Sync // forces a complete resync between the termbox and a terminal, it may not be // visually pretty though.
[ "Sync", "comes", "handy", "when", "something", "causes", "desync", "between", "termbox", "s", "understanding", "of", "a", "terminal", "buffer", "and", "the", "reality", ".", "Such", "as", "a", "third", "party", "process", ".", "Sync", "forces", "a", "complete", "resync", "between", "the", "termbox", "and", "a", "terminal", "it", "may", "not", "be", "visually", "pretty", "though", "." ]
288510b9734e30e7966ec2f22b87c5f8e67345e3
https://github.com/nsf/termbox-go/blob/288510b9734e30e7966ec2f22b87c5f8e67345e3/api.go#L489-L497
train
tus/tusd
metrics.go
incRequestsTotal
func (m Metrics) incRequestsTotal(method string) { if ptr, ok := m.RequestsTotal[method]; ok { atomic.AddUint64(ptr, 1) } }
go
func (m Metrics) incRequestsTotal(method string) { if ptr, ok := m.RequestsTotal[method]; ok { atomic.AddUint64(ptr, 1) } }
[ "func", "(", "m", "Metrics", ")", "incRequestsTotal", "(", "method", "string", ")", "{", "if", "ptr", ",", "ok", ":=", "m", ".", "RequestsTotal", "[", "method", "]", ";", "ok", "{", "atomic", ".", "AddUint64", "(", "ptr", ",", "1", ")", "\n", "}", "\n", "}" ]
// incRequestsTotal increases the counter for this request method atomically by // one. The method must be one of GET, HEAD, POST, PATCH, DELETE.
[ "incRequestsTotal", "increases", "the", "counter", "for", "this", "request", "method", "atomically", "by", "one", ".", "The", "method", "must", "be", "one", "of", "GET", "HEAD", "POST", "PATCH", "DELETE", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/metrics.go#L27-L31
train
tus/tusd
metrics.go
incErrorsTotal
func (m Metrics) incErrorsTotal(err HTTPError) { ptr := m.ErrorsTotal.retrievePointerFor(err) atomic.AddUint64(ptr, 1) }
go
func (m Metrics) incErrorsTotal(err HTTPError) { ptr := m.ErrorsTotal.retrievePointerFor(err) atomic.AddUint64(ptr, 1) }
[ "func", "(", "m", "Metrics", ")", "incErrorsTotal", "(", "err", "HTTPError", ")", "{", "ptr", ":=", "m", ".", "ErrorsTotal", ".", "retrievePointerFor", "(", "err", ")", "\n", "atomic", ".", "AddUint64", "(", "ptr", ",", "1", ")", "\n", "}" ]
// incErrorsTotal increases the counter for this error atomically by one.
[ "incErrorsTotal", "increases", "the", "counter", "for", "this", "error", "atomically", "by", "one", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/metrics.go#L34-L37
train
tus/tusd
metrics.go
incBytesReceived
func (m Metrics) incBytesReceived(delta uint64) { atomic.AddUint64(m.BytesReceived, delta) }
go
func (m Metrics) incBytesReceived(delta uint64) { atomic.AddUint64(m.BytesReceived, delta) }
[ "func", "(", "m", "Metrics", ")", "incBytesReceived", "(", "delta", "uint64", ")", "{", "atomic", ".", "AddUint64", "(", "m", ".", "BytesReceived", ",", "delta", ")", "\n", "}" ]
// incBytesReceived increases the number of received bytes atomically be the // specified number.
[ "incBytesReceived", "increases", "the", "number", "of", "received", "bytes", "atomically", "be", "the", "specified", "number", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/metrics.go#L41-L43
train
tus/tusd
metrics.go
Load
func (e *ErrorsTotalMap) Load() map[HTTPError]*uint64 { m := make(map[HTTPError]*uint64, len(e.counter)) e.lock.RLock() for err, ptr := range e.counter { httpErr := NewHTTPError(errors.New(err.Message), err.StatusCode) m[httpErr] = ptr } e.lock.RUnlock() return m }
go
func (e *ErrorsTotalMap) Load() map[HTTPError]*uint64 { m := make(map[HTTPError]*uint64, len(e.counter)) e.lock.RLock() for err, ptr := range e.counter { httpErr := NewHTTPError(errors.New(err.Message), err.StatusCode) m[httpErr] = ptr } e.lock.RUnlock() return m }
[ "func", "(", "e", "*", "ErrorsTotalMap", ")", "Load", "(", ")", "map", "[", "HTTPError", "]", "*", "uint64", "{", "m", ":=", "make", "(", "map", "[", "HTTPError", "]", "*", "uint64", ",", "len", "(", "e", ".", "counter", ")", ")", "\n", "e", ".", "lock", ".", "RLock", "(", ")", "\n", "for", "err", ",", "ptr", ":=", "range", "e", ".", "counter", "{", "httpErr", ":=", "NewHTTPError", "(", "errors", ".", "New", "(", "err", ".", "Message", ")", ",", "err", ".", "StatusCode", ")", "\n", "m", "[", "httpErr", "]", "=", "ptr", "\n", "}", "\n", "e", ".", "lock", ".", "RUnlock", "(", ")", "\n\n", "return", "m", "\n", "}" ]
// Load retrieves the map of the counter pointers atomically
[ "Load", "retrieves", "the", "map", "of", "the", "counter", "pointers", "atomically" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/metrics.go#L127-L137
train
tus/tusd
etcd3locker/locker_options.go
Prefix
func (l *LockerOptions) Prefix() string { prefix := l.prefix if !strings.HasPrefix(prefix, "/") { prefix = "/" + prefix } if prefix == "" { return DefaultPrefix } else { return prefix } }
go
func (l *LockerOptions) Prefix() string { prefix := l.prefix if !strings.HasPrefix(prefix, "/") { prefix = "/" + prefix } if prefix == "" { return DefaultPrefix } else { return prefix } }
[ "func", "(", "l", "*", "LockerOptions", ")", "Prefix", "(", ")", "string", "{", "prefix", ":=", "l", ".", "prefix", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "prefix", ",", "\"", "\"", ")", "{", "prefix", "=", "\"", "\"", "+", "prefix", "\n", "}", "\n\n", "if", "prefix", "==", "\"", "\"", "{", "return", "DefaultPrefix", "\n", "}", "else", "{", "return", "prefix", "\n", "}", "\n", "}" ]
// Returns the string prefix used to store keys in etcd3
[ "Returns", "the", "string", "prefix", "used", "to", "store", "keys", "in", "etcd3" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/etcd3locker/locker_options.go#L45-L56
train
tus/tusd
limitedstore/limitedstore.go
New
func New(storeSize int64, dataStore tusd.DataStore, terminater tusd.TerminaterDataStore) *LimitedStore { return &LimitedStore{ StoreSize: storeSize, DataStore: dataStore, terminater: terminater, uploads: make(map[string]int64), mutex: new(sync.Mutex), } }
go
func New(storeSize int64, dataStore tusd.DataStore, terminater tusd.TerminaterDataStore) *LimitedStore { return &LimitedStore{ StoreSize: storeSize, DataStore: dataStore, terminater: terminater, uploads: make(map[string]int64), mutex: new(sync.Mutex), } }
[ "func", "New", "(", "storeSize", "int64", ",", "dataStore", "tusd", ".", "DataStore", ",", "terminater", "tusd", ".", "TerminaterDataStore", ")", "*", "LimitedStore", "{", "return", "&", "LimitedStore", "{", "StoreSize", ":", "storeSize", ",", "DataStore", ":", "dataStore", ",", "terminater", ":", "terminater", ",", "uploads", ":", "make", "(", "map", "[", "string", "]", "int64", ")", ",", "mutex", ":", "new", "(", "sync", ".", "Mutex", ")", ",", "}", "\n", "}" ]
// New creates a new limited store with the given size as the maximum storage // size. The wrapped data store needs to implement the TerminaterDataStore // interface, in order to provide the required Terminate method.
[ "New", "creates", "a", "new", "limited", "store", "with", "the", "given", "size", "as", "the", "maximum", "storage", "size", ".", "The", "wrapped", "data", "store", "needs", "to", "implement", "the", "TerminaterDataStore", "interface", "in", "order", "to", "provide", "the", "required", "Terminate", "method", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/limitedstore/limitedstore.go#L52-L60
train
tus/tusd
limitedstore/limitedstore.go
ensureSpace
func (store *LimitedStore) ensureSpace(size int64) error { if (store.usedSize + size) <= store.StoreSize { // Enough space is available to store the new upload return nil } sortedUploads := make(pairlist, len(store.uploads)) i := 0 for u, h := range store.uploads { sortedUploads[i] = pair{u, h} i++ } sort.Sort(sort.Reverse(sortedUploads)) // Forward traversal through the uploads in terms of size, biggest upload first for _, k := range sortedUploads { id := k.key if err := store.terminate(id); err != nil { return err } if (store.usedSize + size) <= store.StoreSize { // Enough space has been freed to store the new upload return nil } } return nil }
go
func (store *LimitedStore) ensureSpace(size int64) error { if (store.usedSize + size) <= store.StoreSize { // Enough space is available to store the new upload return nil } sortedUploads := make(pairlist, len(store.uploads)) i := 0 for u, h := range store.uploads { sortedUploads[i] = pair{u, h} i++ } sort.Sort(sort.Reverse(sortedUploads)) // Forward traversal through the uploads in terms of size, biggest upload first for _, k := range sortedUploads { id := k.key if err := store.terminate(id); err != nil { return err } if (store.usedSize + size) <= store.StoreSize { // Enough space has been freed to store the new upload return nil } } return nil }
[ "func", "(", "store", "*", "LimitedStore", ")", "ensureSpace", "(", "size", "int64", ")", "error", "{", "if", "(", "store", ".", "usedSize", "+", "size", ")", "<=", "store", ".", "StoreSize", "{", "// Enough space is available to store the new upload", "return", "nil", "\n", "}", "\n\n", "sortedUploads", ":=", "make", "(", "pairlist", ",", "len", "(", "store", ".", "uploads", ")", ")", "\n", "i", ":=", "0", "\n", "for", "u", ",", "h", ":=", "range", "store", ".", "uploads", "{", "sortedUploads", "[", "i", "]", "=", "pair", "{", "u", ",", "h", "}", "\n", "i", "++", "\n", "}", "\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "sortedUploads", ")", ")", "\n\n", "// Forward traversal through the uploads in terms of size, biggest upload first", "for", "_", ",", "k", ":=", "range", "sortedUploads", "{", "id", ":=", "k", ".", "key", "\n\n", "if", "err", ":=", "store", ".", "terminate", "(", "id", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "(", "store", ".", "usedSize", "+", "size", ")", "<=", "store", ".", "StoreSize", "{", "// Enough space has been freed to store the new upload", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Ensure enough space is available to store an upload of the specified size. // It will terminate uploads until enough space is freed.
[ "Ensure", "enough", "space", "is", "available", "to", "store", "an", "upload", "of", "the", "specified", "size", ".", "It", "will", "terminate", "uploads", "until", "enough", "space", "is", "freed", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/limitedstore/limitedstore.go#L111-L140
train
tus/tusd
filestore/filestore.go
newLock
func (store FileStore) newLock(id string) (lockfile.Lockfile, error) { path, err := filepath.Abs(filepath.Join(store.Path, id+".lock")) if err != nil { return lockfile.Lockfile(""), err } // We use Lockfile directly instead of lockfile.New to bypass the unnecessary // check whether the provided path is absolute since we just resolved it // on our own. return lockfile.Lockfile(path), nil }
go
func (store FileStore) newLock(id string) (lockfile.Lockfile, error) { path, err := filepath.Abs(filepath.Join(store.Path, id+".lock")) if err != nil { return lockfile.Lockfile(""), err } // We use Lockfile directly instead of lockfile.New to bypass the unnecessary // check whether the provided path is absolute since we just resolved it // on our own. return lockfile.Lockfile(path), nil }
[ "func", "(", "store", "FileStore", ")", "newLock", "(", "id", "string", ")", "(", "lockfile", ".", "Lockfile", ",", "error", ")", "{", "path", ",", "err", ":=", "filepath", ".", "Abs", "(", "filepath", ".", "Join", "(", "store", ".", "Path", ",", "id", "+", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "lockfile", ".", "Lockfile", "(", "\"", "\"", ")", ",", "err", "\n", "}", "\n\n", "// We use Lockfile directly instead of lockfile.New to bypass the unnecessary", "// check whether the provided path is absolute since we just resolved it", "// on our own.", "return", "lockfile", ".", "Lockfile", "(", "path", ")", ",", "nil", "\n", "}" ]
// newLock contructs a new Lockfile instance.
[ "newLock", "contructs", "a", "new", "Lockfile", "instance", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/filestore/filestore.go#L189-L199
train
tus/tusd
filestore/filestore.go
binPath
func (store FileStore) binPath(id string) string { return filepath.Join(store.Path, id+".bin") }
go
func (store FileStore) binPath(id string) string { return filepath.Join(store.Path, id+".bin") }
[ "func", "(", "store", "FileStore", ")", "binPath", "(", "id", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "store", ".", "Path", ",", "id", "+", "\"", "\"", ")", "\n", "}" ]
// binPath returns the path to the .bin storing the binary data.
[ "binPath", "returns", "the", "path", "to", "the", ".", "bin", "storing", "the", "binary", "data", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/filestore/filestore.go#L202-L204
train
tus/tusd
filestore/filestore.go
infoPath
func (store FileStore) infoPath(id string) string { return filepath.Join(store.Path, id+".info") }
go
func (store FileStore) infoPath(id string) string { return filepath.Join(store.Path, id+".info") }
[ "func", "(", "store", "FileStore", ")", "infoPath", "(", "id", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "store", ".", "Path", ",", "id", "+", "\"", "\"", ")", "\n", "}" ]
// infoPath returns the path to the .info file storing the file's info.
[ "infoPath", "returns", "the", "path", "to", "the", ".", "info", "file", "storing", "the", "file", "s", "info", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/filestore/filestore.go#L207-L209
train
tus/tusd
filestore/filestore.go
writeInfo
func (store FileStore) writeInfo(id string, info tusd.FileInfo) error { data, err := json.Marshal(info) if err != nil { return err } return ioutil.WriteFile(store.infoPath(id), data, defaultFilePerm) }
go
func (store FileStore) writeInfo(id string, info tusd.FileInfo) error { data, err := json.Marshal(info) if err != nil { return err } return ioutil.WriteFile(store.infoPath(id), data, defaultFilePerm) }
[ "func", "(", "store", "FileStore", ")", "writeInfo", "(", "id", "string", ",", "info", "tusd", ".", "FileInfo", ")", "error", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "info", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ioutil", ".", "WriteFile", "(", "store", ".", "infoPath", "(", "id", ")", ",", "data", ",", "defaultFilePerm", ")", "\n", "}" ]
// writeInfo updates the entire information. Everything will be overwritten.
[ "writeInfo", "updates", "the", "entire", "information", ".", "Everything", "will", "be", "overwritten", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/filestore/filestore.go#L212-L218
train
tus/tusd
consullocker/consullocker.go
New
func New(client *consul.Client) *ConsulLocker { return &ConsulLocker{ Client: client, locks: make(map[string]*consul.Lock), mutex: new(sync.RWMutex), } }
go
func New(client *consul.Client) *ConsulLocker { return &ConsulLocker{ Client: client, locks: make(map[string]*consul.Lock), mutex: new(sync.RWMutex), } }
[ "func", "New", "(", "client", "*", "consul", ".", "Client", ")", "*", "ConsulLocker", "{", "return", "&", "ConsulLocker", "{", "Client", ":", "client", ",", "locks", ":", "make", "(", "map", "[", "string", "]", "*", "consul", ".", "Lock", ")", ",", "mutex", ":", "new", "(", "sync", ".", "RWMutex", ")", ",", "}", "\n", "}" ]
// New constructs a new locker using the provided client.
[ "New", "constructs", "a", "new", "locker", "using", "the", "provided", "client", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/consullocker/consullocker.go#L40-L46
train
tus/tusd
unrouted_handler.go
Middleware
func (handler *UnroutedHandler) Middleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Allow overriding the HTTP method. The reason for this is // that some libraries/environments to not support PATCH and // DELETE requests, e.g. Flash in a browser and parts of Java if newMethod := r.Header.Get("X-HTTP-Method-Override"); newMethod != "" { r.Method = newMethod } handler.log("RequestIncoming", "method", r.Method, "path", r.URL.Path) handler.Metrics.incRequestsTotal(r.Method) header := w.Header() if origin := r.Header.Get("Origin"); origin != "" { header.Set("Access-Control-Allow-Origin", origin) if r.Method == "OPTIONS" { // Preflight request header.Add("Access-Control-Allow-Methods", "POST, GET, HEAD, PATCH, DELETE, OPTIONS") header.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata, Upload-Defer-Length, Upload-Concat") header.Set("Access-Control-Max-Age", "86400") } else { // Actual request header.Add("Access-Control-Expose-Headers", "Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, Upload-Defer-Length, Upload-Concat") } } // Set current version used by the server header.Set("Tus-Resumable", "1.0.0") // Add nosniff to all responses https://golang.org/src/net/http/server.go#L1429 header.Set("X-Content-Type-Options", "nosniff") // Set appropriated headers in case of OPTIONS method allowing protocol // discovery and end with an 204 No Content if r.Method == "OPTIONS" { if handler.config.MaxSize > 0 { header.Set("Tus-Max-Size", strconv.FormatInt(handler.config.MaxSize, 10)) } header.Set("Tus-Version", "1.0.0") header.Set("Tus-Extension", handler.extensions) // Although the 204 No Content status code is a better fit in this case, // since we do not have a response body included, we cannot use it here // as some browsers only accept 200 OK as successful response to a // preflight request. If we send them the 204 No Content the response // will be ignored or interpreted as a rejection. // For example, the Presto engine, which is used in older versions of // Opera, Opera Mobile and Opera Mini, handles CORS this way. handler.sendResp(w, r, http.StatusOK) return } // Test if the version sent by the client is supported // GET methods are not checked since a browser may visit this URL and does // not include this header. This request is not part of the specification. if r.Method != "GET" && r.Header.Get("Tus-Resumable") != "1.0.0" { handler.sendError(w, r, ErrUnsupportedVersion) return } // Proceed with routing the request h.ServeHTTP(w, r) }) }
go
func (handler *UnroutedHandler) Middleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Allow overriding the HTTP method. The reason for this is // that some libraries/environments to not support PATCH and // DELETE requests, e.g. Flash in a browser and parts of Java if newMethod := r.Header.Get("X-HTTP-Method-Override"); newMethod != "" { r.Method = newMethod } handler.log("RequestIncoming", "method", r.Method, "path", r.URL.Path) handler.Metrics.incRequestsTotal(r.Method) header := w.Header() if origin := r.Header.Get("Origin"); origin != "" { header.Set("Access-Control-Allow-Origin", origin) if r.Method == "OPTIONS" { // Preflight request header.Add("Access-Control-Allow-Methods", "POST, GET, HEAD, PATCH, DELETE, OPTIONS") header.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata, Upload-Defer-Length, Upload-Concat") header.Set("Access-Control-Max-Age", "86400") } else { // Actual request header.Add("Access-Control-Expose-Headers", "Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, Upload-Defer-Length, Upload-Concat") } } // Set current version used by the server header.Set("Tus-Resumable", "1.0.0") // Add nosniff to all responses https://golang.org/src/net/http/server.go#L1429 header.Set("X-Content-Type-Options", "nosniff") // Set appropriated headers in case of OPTIONS method allowing protocol // discovery and end with an 204 No Content if r.Method == "OPTIONS" { if handler.config.MaxSize > 0 { header.Set("Tus-Max-Size", strconv.FormatInt(handler.config.MaxSize, 10)) } header.Set("Tus-Version", "1.0.0") header.Set("Tus-Extension", handler.extensions) // Although the 204 No Content status code is a better fit in this case, // since we do not have a response body included, we cannot use it here // as some browsers only accept 200 OK as successful response to a // preflight request. If we send them the 204 No Content the response // will be ignored or interpreted as a rejection. // For example, the Presto engine, which is used in older versions of // Opera, Opera Mobile and Opera Mini, handles CORS this way. handler.sendResp(w, r, http.StatusOK) return } // Test if the version sent by the client is supported // GET methods are not checked since a browser may visit this URL and does // not include this header. This request is not part of the specification. if r.Method != "GET" && r.Header.Get("Tus-Resumable") != "1.0.0" { handler.sendError(w, r, ErrUnsupportedVersion) return } // Proceed with routing the request h.ServeHTTP(w, r) }) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "Middleware", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Allow overriding the HTTP method. The reason for this is", "// that some libraries/environments to not support PATCH and", "// DELETE requests, e.g. Flash in a browser and parts of Java", "if", "newMethod", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "newMethod", "!=", "\"", "\"", "{", "r", ".", "Method", "=", "newMethod", "\n", "}", "\n\n", "handler", ".", "log", "(", "\"", "\"", ",", "\"", "\"", ",", "r", ".", "Method", ",", "\"", "\"", ",", "r", ".", "URL", ".", "Path", ")", "\n\n", "handler", ".", "Metrics", ".", "incRequestsTotal", "(", "r", ".", "Method", ")", "\n\n", "header", ":=", "w", ".", "Header", "(", ")", "\n\n", "if", "origin", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "origin", "!=", "\"", "\"", "{", "header", ".", "Set", "(", "\"", "\"", ",", "origin", ")", "\n\n", "if", "r", ".", "Method", "==", "\"", "\"", "{", "// Preflight request", "header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "}", "else", "{", "// Actual request", "header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// Set current version used by the server", "header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Add nosniff to all responses https://golang.org/src/net/http/server.go#L1429", "header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Set appropriated headers in case of OPTIONS method allowing protocol", "// discovery and end with an 204 No Content", "if", "r", ".", "Method", "==", "\"", "\"", "{", "if", "handler", ".", "config", ".", "MaxSize", ">", "0", "{", "header", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "handler", ".", "config", ".", "MaxSize", ",", "10", ")", ")", "\n", "}", "\n\n", "header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "header", ".", "Set", "(", "\"", "\"", ",", "handler", ".", "extensions", ")", "\n\n", "// Although the 204 No Content status code is a better fit in this case,", "// since we do not have a response body included, we cannot use it here", "// as some browsers only accept 200 OK as successful response to a", "// preflight request. If we send them the 204 No Content the response", "// will be ignored or interpreted as a rejection.", "// For example, the Presto engine, which is used in older versions of", "// Opera, Opera Mobile and Opera Mini, handles CORS this way.", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusOK", ")", "\n", "return", "\n", "}", "\n\n", "// Test if the version sent by the client is supported", "// GET methods are not checked since a browser may visit this URL and does", "// not include this header. This request is not part of the specification.", "if", "r", ".", "Method", "!=", "\"", "\"", "&&", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "ErrUnsupportedVersion", ")", "\n", "return", "\n", "}", "\n\n", "// Proceed with routing the request", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", ")", "\n", "}" ]
// Middleware checks various aspects of the request and ensures that it // conforms with the spec. Also handles method overriding for clients which // cannot make PATCH AND DELETE requests. If you are using the tusd handlers // directly you will need to wrap at least the POST and PATCH endpoints in // this middleware.
[ "Middleware", "checks", "various", "aspects", "of", "the", "request", "and", "ensures", "that", "it", "conforms", "with", "the", "spec", ".", "Also", "handles", "method", "overriding", "for", "clients", "which", "cannot", "make", "PATCH", "AND", "DELETE", "requests", ".", "If", "you", "are", "using", "the", "tusd", "handlers", "directly", "you", "will", "need", "to", "wrap", "at", "least", "the", "POST", "and", "PATCH", "endpoints", "in", "this", "middleware", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L161-L229
train
tus/tusd
unrouted_handler.go
HeadFile
func (handler *UnroutedHandler) HeadFile(w http.ResponseWriter, r *http.Request) { id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } info, err := handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } // Add Upload-Concat header if possible if info.IsPartial { w.Header().Set("Upload-Concat", "partial") } if info.IsFinal { v := "final;" for _, uploadID := range info.PartialUploads { v += handler.absFileURL(r, uploadID) + " " } // Remove trailing space v = v[:len(v)-1] w.Header().Set("Upload-Concat", v) } if len(info.MetaData) != 0 { w.Header().Set("Upload-Metadata", SerializeMetadataHeader(info.MetaData)) } if info.SizeIsDeferred { w.Header().Set("Upload-Defer-Length", UploadLengthDeferred) } else { w.Header().Set("Upload-Length", strconv.FormatInt(info.Size, 10)) } w.Header().Set("Cache-Control", "no-store") w.Header().Set("Upload-Offset", strconv.FormatInt(info.Offset, 10)) handler.sendResp(w, r, http.StatusOK) }
go
func (handler *UnroutedHandler) HeadFile(w http.ResponseWriter, r *http.Request) { id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } info, err := handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } // Add Upload-Concat header if possible if info.IsPartial { w.Header().Set("Upload-Concat", "partial") } if info.IsFinal { v := "final;" for _, uploadID := range info.PartialUploads { v += handler.absFileURL(r, uploadID) + " " } // Remove trailing space v = v[:len(v)-1] w.Header().Set("Upload-Concat", v) } if len(info.MetaData) != 0 { w.Header().Set("Upload-Metadata", SerializeMetadataHeader(info.MetaData)) } if info.SizeIsDeferred { w.Header().Set("Upload-Defer-Length", UploadLengthDeferred) } else { w.Header().Set("Upload-Length", strconv.FormatInt(info.Size, 10)) } w.Header().Set("Cache-Control", "no-store") w.Header().Set("Upload-Offset", strconv.FormatInt(info.Offset, 10)) handler.sendResp(w, r, http.StatusOK) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "HeadFile", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "id", ",", "err", ":=", "extractIDFromPath", "(", "r", ".", "URL", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "handler", ".", "composer", ".", "UsesLocker", "{", "locker", ":=", "handler", ".", "composer", ".", "Locker", "\n", "if", "err", ":=", "locker", ".", "LockUpload", "(", "id", ")", ";", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "defer", "locker", ".", "UnlockUpload", "(", "id", ")", "\n", "}", "\n\n", "info", ",", "err", ":=", "handler", ".", "composer", ".", "Core", ".", "GetInfo", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Add Upload-Concat header if possible", "if", "info", ".", "IsPartial", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "info", ".", "IsFinal", "{", "v", ":=", "\"", "\"", "\n", "for", "_", ",", "uploadID", ":=", "range", "info", ".", "PartialUploads", "{", "v", "+=", "handler", ".", "absFileURL", "(", "r", ",", "uploadID", ")", "+", "\"", "\"", "\n", "}", "\n", "// Remove trailing space", "v", "=", "v", "[", ":", "len", "(", "v", ")", "-", "1", "]", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n\n", "if", "len", "(", "info", ".", "MetaData", ")", "!=", "0", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "SerializeMetadataHeader", "(", "info", ".", "MetaData", ")", ")", "\n", "}", "\n\n", "if", "info", ".", "SizeIsDeferred", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "UploadLengthDeferred", ")", "\n", "}", "else", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "info", ".", "Size", ",", "10", ")", ")", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "info", ".", "Offset", ",", "10", ")", ")", "\n", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusOK", ")", "\n", "}" ]
// HeadFile returns the length and offset for the HEAD request
[ "HeadFile", "returns", "the", "length", "and", "offset", "for", "the", "HEAD", "request" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L356-L409
train
tus/tusd
unrouted_handler.go
writeChunk
func (handler *UnroutedHandler) writeChunk(id string, info FileInfo, w http.ResponseWriter, r *http.Request) error { // Get Content-Length if possible length := r.ContentLength offset := info.Offset // Test if this upload fits into the file's size if !info.SizeIsDeferred && offset+length > info.Size { return ErrSizeExceeded } maxSize := info.Size - offset // If the upload's length is deferred and the PATCH request does not contain the Content-Length // header (which is allowed if 'Transfer-Encoding: chunked' is used), we still need to set limits for // the body size. if info.SizeIsDeferred { if handler.config.MaxSize > 0 { // Ensure that the upload does not exceed the maximum upload size maxSize = handler.config.MaxSize - offset } else { // If no upload limit is given, we allow arbitrary sizes maxSize = math.MaxInt64 } } if length > 0 { maxSize = length } handler.log("ChunkWriteStart", "id", id, "maxSize", i64toa(maxSize), "offset", i64toa(offset)) var bytesWritten int64 // Prevent a nil pointer dereference when accessing the body which may not be // available in the case of a malicious request. if r.Body != nil { // Limit the data read from the request's body to the allowed maximum reader := io.LimitReader(r.Body, maxSize) if handler.config.NotifyUploadProgress { var stop chan<- struct{} reader, stop = handler.sendProgressMessages(info, reader) defer close(stop) } var err error bytesWritten, err = handler.composer.Core.WriteChunk(id, offset, reader) if err != nil { return err } } handler.log("ChunkWriteComplete", "id", id, "bytesWritten", i64toa(bytesWritten)) // Send new offset to client newOffset := offset + bytesWritten w.Header().Set("Upload-Offset", strconv.FormatInt(newOffset, 10)) handler.Metrics.incBytesReceived(uint64(bytesWritten)) info.Offset = newOffset return handler.finishUploadIfComplete(info) }
go
func (handler *UnroutedHandler) writeChunk(id string, info FileInfo, w http.ResponseWriter, r *http.Request) error { // Get Content-Length if possible length := r.ContentLength offset := info.Offset // Test if this upload fits into the file's size if !info.SizeIsDeferred && offset+length > info.Size { return ErrSizeExceeded } maxSize := info.Size - offset // If the upload's length is deferred and the PATCH request does not contain the Content-Length // header (which is allowed if 'Transfer-Encoding: chunked' is used), we still need to set limits for // the body size. if info.SizeIsDeferred { if handler.config.MaxSize > 0 { // Ensure that the upload does not exceed the maximum upload size maxSize = handler.config.MaxSize - offset } else { // If no upload limit is given, we allow arbitrary sizes maxSize = math.MaxInt64 } } if length > 0 { maxSize = length } handler.log("ChunkWriteStart", "id", id, "maxSize", i64toa(maxSize), "offset", i64toa(offset)) var bytesWritten int64 // Prevent a nil pointer dereference when accessing the body which may not be // available in the case of a malicious request. if r.Body != nil { // Limit the data read from the request's body to the allowed maximum reader := io.LimitReader(r.Body, maxSize) if handler.config.NotifyUploadProgress { var stop chan<- struct{} reader, stop = handler.sendProgressMessages(info, reader) defer close(stop) } var err error bytesWritten, err = handler.composer.Core.WriteChunk(id, offset, reader) if err != nil { return err } } handler.log("ChunkWriteComplete", "id", id, "bytesWritten", i64toa(bytesWritten)) // Send new offset to client newOffset := offset + bytesWritten w.Header().Set("Upload-Offset", strconv.FormatInt(newOffset, 10)) handler.Metrics.incBytesReceived(uint64(bytesWritten)) info.Offset = newOffset return handler.finishUploadIfComplete(info) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "writeChunk", "(", "id", "string", ",", "info", "FileInfo", ",", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "error", "{", "// Get Content-Length if possible", "length", ":=", "r", ".", "ContentLength", "\n", "offset", ":=", "info", ".", "Offset", "\n\n", "// Test if this upload fits into the file's size", "if", "!", "info", ".", "SizeIsDeferred", "&&", "offset", "+", "length", ">", "info", ".", "Size", "{", "return", "ErrSizeExceeded", "\n", "}", "\n\n", "maxSize", ":=", "info", ".", "Size", "-", "offset", "\n", "// If the upload's length is deferred and the PATCH request does not contain the Content-Length", "// header (which is allowed if 'Transfer-Encoding: chunked' is used), we still need to set limits for", "// the body size.", "if", "info", ".", "SizeIsDeferred", "{", "if", "handler", ".", "config", ".", "MaxSize", ">", "0", "{", "// Ensure that the upload does not exceed the maximum upload size", "maxSize", "=", "handler", ".", "config", ".", "MaxSize", "-", "offset", "\n", "}", "else", "{", "// If no upload limit is given, we allow arbitrary sizes", "maxSize", "=", "math", ".", "MaxInt64", "\n", "}", "\n", "}", "\n", "if", "length", ">", "0", "{", "maxSize", "=", "length", "\n", "}", "\n\n", "handler", ".", "log", "(", "\"", "\"", ",", "\"", "\"", ",", "id", ",", "\"", "\"", ",", "i64toa", "(", "maxSize", ")", ",", "\"", "\"", ",", "i64toa", "(", "offset", ")", ")", "\n\n", "var", "bytesWritten", "int64", "\n", "// Prevent a nil pointer dereference when accessing the body which may not be", "// available in the case of a malicious request.", "if", "r", ".", "Body", "!=", "nil", "{", "// Limit the data read from the request's body to the allowed maximum", "reader", ":=", "io", ".", "LimitReader", "(", "r", ".", "Body", ",", "maxSize", ")", "\n\n", "if", "handler", ".", "config", ".", "NotifyUploadProgress", "{", "var", "stop", "chan", "<-", "struct", "{", "}", "\n", "reader", ",", "stop", "=", "handler", ".", "sendProgressMessages", "(", "info", ",", "reader", ")", "\n", "defer", "close", "(", "stop", ")", "\n", "}", "\n\n", "var", "err", "error", "\n", "bytesWritten", ",", "err", "=", "handler", ".", "composer", ".", "Core", ".", "WriteChunk", "(", "id", ",", "offset", ",", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "handler", ".", "log", "(", "\"", "\"", ",", "\"", "\"", ",", "id", ",", "\"", "\"", ",", "i64toa", "(", "bytesWritten", ")", ")", "\n\n", "// Send new offset to client", "newOffset", ":=", "offset", "+", "bytesWritten", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "newOffset", ",", "10", ")", ")", "\n", "handler", ".", "Metrics", ".", "incBytesReceived", "(", "uint64", "(", "bytesWritten", ")", ")", "\n", "info", ".", "Offset", "=", "newOffset", "\n\n", "return", "handler", ".", "finishUploadIfComplete", "(", "info", ")", "\n", "}" ]
// writeChunk reads the body from the requests r and appends it to the upload // with the corresponding id. Afterwards, it will set the necessary response // headers but will not send the response.
[ "writeChunk", "reads", "the", "body", "from", "the", "requests", "r", "and", "appends", "it", "to", "the", "upload", "with", "the", "corresponding", "id", ".", "Afterwards", "it", "will", "set", "the", "necessary", "response", "headers", "but", "will", "not", "send", "the", "response", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L502-L560
train
tus/tusd
unrouted_handler.go
GetFile
func (handler *UnroutedHandler) GetFile(w http.ResponseWriter, r *http.Request) { if !handler.composer.UsesGetReader { handler.sendError(w, r, ErrNotImplemented) return } id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } info, err := handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } // Set headers before sending responses w.Header().Set("Content-Length", strconv.FormatInt(info.Offset, 10)) contentType, contentDisposition := filterContentType(info) w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Disposition", contentDisposition) // If no data has been uploaded yet, respond with an empty "204 No Content" status. if info.Offset == 0 { handler.sendResp(w, r, http.StatusNoContent) return } src, err := handler.composer.GetReader.GetReader(id) if err != nil { handler.sendError(w, r, err) return } handler.sendResp(w, r, http.StatusOK) io.Copy(w, src) // Try to close the reader if the io.Closer interface is implemented if closer, ok := src.(io.Closer); ok { closer.Close() } }
go
func (handler *UnroutedHandler) GetFile(w http.ResponseWriter, r *http.Request) { if !handler.composer.UsesGetReader { handler.sendError(w, r, ErrNotImplemented) return } id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } info, err := handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } // Set headers before sending responses w.Header().Set("Content-Length", strconv.FormatInt(info.Offset, 10)) contentType, contentDisposition := filterContentType(info) w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Disposition", contentDisposition) // If no data has been uploaded yet, respond with an empty "204 No Content" status. if info.Offset == 0 { handler.sendResp(w, r, http.StatusNoContent) return } src, err := handler.composer.GetReader.GetReader(id) if err != nil { handler.sendError(w, r, err) return } handler.sendResp(w, r, http.StatusOK) io.Copy(w, src) // Try to close the reader if the io.Closer interface is implemented if closer, ok := src.(io.Closer); ok { closer.Close() } }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "GetFile", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "!", "handler", ".", "composer", ".", "UsesGetReader", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "ErrNotImplemented", ")", "\n", "return", "\n", "}", "\n\n", "id", ",", "err", ":=", "extractIDFromPath", "(", "r", ".", "URL", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "handler", ".", "composer", ".", "UsesLocker", "{", "locker", ":=", "handler", ".", "composer", ".", "Locker", "\n", "if", "err", ":=", "locker", ".", "LockUpload", "(", "id", ")", ";", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "defer", "locker", ".", "UnlockUpload", "(", "id", ")", "\n", "}", "\n\n", "info", ",", "err", ":=", "handler", ".", "composer", ".", "Core", ".", "GetInfo", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Set headers before sending responses", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "FormatInt", "(", "info", ".", "Offset", ",", "10", ")", ")", "\n\n", "contentType", ",", "contentDisposition", ":=", "filterContentType", "(", "info", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "contentType", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "contentDisposition", ")", "\n\n", "// If no data has been uploaded yet, respond with an empty \"204 No Content\" status.", "if", "info", ".", "Offset", "==", "0", "{", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusNoContent", ")", "\n", "return", "\n", "}", "\n\n", "src", ",", "err", ":=", "handler", ".", "composer", ".", "GetReader", ".", "GetReader", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusOK", ")", "\n", "io", ".", "Copy", "(", "w", ",", "src", ")", "\n\n", "// Try to close the reader if the io.Closer interface is implemented", "if", "closer", ",", "ok", ":=", "src", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "closer", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// GetFile handles requests to download a file using a GET request. This is not // part of the specification.
[ "GetFile", "handles", "requests", "to", "download", "a", "file", "using", "a", "GET", "request", ".", "This", "is", "not", "part", "of", "the", "specification", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L588-L642
train
tus/tusd
unrouted_handler.go
DelFile
func (handler *UnroutedHandler) DelFile(w http.ResponseWriter, r *http.Request) { // Abort the request handling if the required interface is not implemented if !handler.composer.UsesTerminater { handler.sendError(w, r, ErrNotImplemented) return } id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } var info FileInfo if handler.config.NotifyTerminatedUploads { info, err = handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } } err = handler.composer.Terminater.Terminate(id) if err != nil { handler.sendError(w, r, err) return } handler.sendResp(w, r, http.StatusNoContent) if handler.config.NotifyTerminatedUploads { handler.TerminatedUploads <- info } handler.Metrics.incUploadsTerminated() }
go
func (handler *UnroutedHandler) DelFile(w http.ResponseWriter, r *http.Request) { // Abort the request handling if the required interface is not implemented if !handler.composer.UsesTerminater { handler.sendError(w, r, ErrNotImplemented) return } id, err := extractIDFromPath(r.URL.Path) if err != nil { handler.sendError(w, r, err) return } if handler.composer.UsesLocker { locker := handler.composer.Locker if err := locker.LockUpload(id); err != nil { handler.sendError(w, r, err) return } defer locker.UnlockUpload(id) } var info FileInfo if handler.config.NotifyTerminatedUploads { info, err = handler.composer.Core.GetInfo(id) if err != nil { handler.sendError(w, r, err) return } } err = handler.composer.Terminater.Terminate(id) if err != nil { handler.sendError(w, r, err) return } handler.sendResp(w, r, http.StatusNoContent) if handler.config.NotifyTerminatedUploads { handler.TerminatedUploads <- info } handler.Metrics.incUploadsTerminated() }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "DelFile", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Abort the request handling if the required interface is not implemented", "if", "!", "handler", ".", "composer", ".", "UsesTerminater", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "ErrNotImplemented", ")", "\n", "return", "\n", "}", "\n\n", "id", ",", "err", ":=", "extractIDFromPath", "(", "r", ".", "URL", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "handler", ".", "composer", ".", "UsesLocker", "{", "locker", ":=", "handler", ".", "composer", ".", "Locker", "\n", "if", "err", ":=", "locker", ".", "LockUpload", "(", "id", ")", ";", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "defer", "locker", ".", "UnlockUpload", "(", "id", ")", "\n", "}", "\n\n", "var", "info", "FileInfo", "\n", "if", "handler", ".", "config", ".", "NotifyTerminatedUploads", "{", "info", ",", "err", "=", "handler", ".", "composer", ".", "Core", ".", "GetInfo", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "err", "=", "handler", ".", "composer", ".", "Terminater", ".", "Terminate", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "handler", ".", "sendError", "(", "w", ",", "r", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "handler", ".", "sendResp", "(", "w", ",", "r", ",", "http", ".", "StatusNoContent", ")", "\n\n", "if", "handler", ".", "config", ".", "NotifyTerminatedUploads", "{", "handler", ".", "TerminatedUploads", "<-", "info", "\n", "}", "\n\n", "handler", ".", "Metrics", ".", "incUploadsTerminated", "(", ")", "\n", "}" ]
// DelFile terminates an upload permanently.
[ "DelFile", "terminates", "an", "upload", "permanently", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L706-L751
train
tus/tusd
unrouted_handler.go
sendError
func (handler *UnroutedHandler) sendError(w http.ResponseWriter, r *http.Request, err error) { // Interpret os.ErrNotExist as 404 Not Found if os.IsNotExist(err) { err = ErrNotFound } // Errors for read timeouts contain too much information which is not // necessary for us and makes grouping for the metrics harder. The error // message looks like: read tcp 127.0.0.1:1080->127.0.0.1:53673: i/o timeout // Therefore, we use a common error message for all of them. if netErr, ok := err.(net.Error); ok && netErr.Timeout() { err = errors.New("read tcp: i/o timeout") } statusErr, ok := err.(HTTPError) if !ok { statusErr = NewHTTPError(err, http.StatusInternalServerError) } reason := append(statusErr.Body(), '\n') if r.Method == "HEAD" { reason = nil } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("Content-Length", strconv.Itoa(len(reason))) w.WriteHeader(statusErr.StatusCode()) w.Write(reason) handler.log("ResponseOutgoing", "status", strconv.Itoa(statusErr.StatusCode()), "method", r.Method, "path", r.URL.Path, "error", err.Error()) handler.Metrics.incErrorsTotal(statusErr) }
go
func (handler *UnroutedHandler) sendError(w http.ResponseWriter, r *http.Request, err error) { // Interpret os.ErrNotExist as 404 Not Found if os.IsNotExist(err) { err = ErrNotFound } // Errors for read timeouts contain too much information which is not // necessary for us and makes grouping for the metrics harder. The error // message looks like: read tcp 127.0.0.1:1080->127.0.0.1:53673: i/o timeout // Therefore, we use a common error message for all of them. if netErr, ok := err.(net.Error); ok && netErr.Timeout() { err = errors.New("read tcp: i/o timeout") } statusErr, ok := err.(HTTPError) if !ok { statusErr = NewHTTPError(err, http.StatusInternalServerError) } reason := append(statusErr.Body(), '\n') if r.Method == "HEAD" { reason = nil } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("Content-Length", strconv.Itoa(len(reason))) w.WriteHeader(statusErr.StatusCode()) w.Write(reason) handler.log("ResponseOutgoing", "status", strconv.Itoa(statusErr.StatusCode()), "method", r.Method, "path", r.URL.Path, "error", err.Error()) handler.Metrics.incErrorsTotal(statusErr) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "sendError", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "err", "error", ")", "{", "// Interpret os.ErrNotExist as 404 Not Found", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", "=", "ErrNotFound", "\n", "}", "\n\n", "// Errors for read timeouts contain too much information which is not", "// necessary for us and makes grouping for the metrics harder. The error", "// message looks like: read tcp 127.0.0.1:1080->127.0.0.1:53673: i/o timeout", "// Therefore, we use a common error message for all of them.", "if", "netErr", ",", "ok", ":=", "err", ".", "(", "net", ".", "Error", ")", ";", "ok", "&&", "netErr", ".", "Timeout", "(", ")", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "statusErr", ",", "ok", ":=", "err", ".", "(", "HTTPError", ")", "\n", "if", "!", "ok", "{", "statusErr", "=", "NewHTTPError", "(", "err", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}", "\n\n", "reason", ":=", "append", "(", "statusErr", ".", "Body", "(", ")", ",", "'\\n'", ")", "\n", "if", "r", ".", "Method", "==", "\"", "\"", "{", "reason", "=", "nil", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "len", "(", "reason", ")", ")", ")", "\n", "w", ".", "WriteHeader", "(", "statusErr", ".", "StatusCode", "(", ")", ")", "\n", "w", ".", "Write", "(", "reason", ")", "\n\n", "handler", ".", "log", "(", "\"", "\"", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "statusErr", ".", "StatusCode", "(", ")", ")", ",", "\"", "\"", ",", "r", ".", "Method", ",", "\"", "\"", ",", "r", ".", "URL", ".", "Path", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n\n", "handler", ".", "Metrics", ".", "incErrorsTotal", "(", "statusErr", ")", "\n", "}" ]
// Send the error in the response body. The status code will be looked up in // ErrStatusCodes. If none is found 500 Internal Error will be used.
[ "Send", "the", "error", "in", "the", "response", "body", ".", "The", "status", "code", "will", "be", "looked", "up", "in", "ErrStatusCodes", ".", "If", "none", "is", "found", "500", "Internal", "Error", "will", "be", "used", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L755-L787
train
tus/tusd
unrouted_handler.go
sendResp
func (handler *UnroutedHandler) sendResp(w http.ResponseWriter, r *http.Request, status int) { w.WriteHeader(status) handler.log("ResponseOutgoing", "status", strconv.Itoa(status), "method", r.Method, "path", r.URL.Path) }
go
func (handler *UnroutedHandler) sendResp(w http.ResponseWriter, r *http.Request, status int) { w.WriteHeader(status) handler.log("ResponseOutgoing", "status", strconv.Itoa(status), "method", r.Method, "path", r.URL.Path) }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "sendResp", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "status", "int", ")", "{", "w", ".", "WriteHeader", "(", "status", ")", "\n\n", "handler", ".", "log", "(", "\"", "\"", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "status", ")", ",", "\"", "\"", ",", "r", ".", "Method", ",", "\"", "\"", ",", "r", ".", "URL", ".", "Path", ")", "\n", "}" ]
// sendResp writes the header to w with the specified status code.
[ "sendResp", "writes", "the", "header", "to", "w", "with", "the", "specified", "status", "code", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L790-L794
train
tus/tusd
unrouted_handler.go
absFileURL
func (handler *UnroutedHandler) absFileURL(r *http.Request, id string) string { if handler.isBasePathAbs { return handler.basePath + id } // Read origin and protocol from request host, proto := getHostAndProtocol(r, handler.config.RespectForwardedHeaders) url := proto + "://" + host + handler.basePath + id return url }
go
func (handler *UnroutedHandler) absFileURL(r *http.Request, id string) string { if handler.isBasePathAbs { return handler.basePath + id } // Read origin and protocol from request host, proto := getHostAndProtocol(r, handler.config.RespectForwardedHeaders) url := proto + "://" + host + handler.basePath + id return url }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "absFileURL", "(", "r", "*", "http", ".", "Request", ",", "id", "string", ")", "string", "{", "if", "handler", ".", "isBasePathAbs", "{", "return", "handler", ".", "basePath", "+", "id", "\n", "}", "\n\n", "// Read origin and protocol from request", "host", ",", "proto", ":=", "getHostAndProtocol", "(", "r", ",", "handler", ".", "config", ".", "RespectForwardedHeaders", ")", "\n\n", "url", ":=", "proto", "+", "\"", "\"", "+", "host", "+", "handler", ".", "basePath", "+", "id", "\n\n", "return", "url", "\n", "}" ]
// Make an absolute URLs to the given upload id. If the base path is absolute // it will be prepended else the host and protocol from the request is used.
[ "Make", "an", "absolute", "URLs", "to", "the", "given", "upload", "id", ".", "If", "the", "base", "path", "is", "absolute", "it", "will", "be", "prepended", "else", "the", "host", "and", "protocol", "from", "the", "request", "is", "used", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L798-L809
train
tus/tusd
unrouted_handler.go
sendProgressMessages
func (handler *UnroutedHandler) sendProgressMessages(info FileInfo, reader io.Reader) (io.Reader, chan<- struct{}) { progress := &progressWriter{ Offset: info.Offset, } stop := make(chan struct{}, 1) reader = io.TeeReader(reader, progress) go func() { for { select { case <-stop: info.Offset = atomic.LoadInt64(&progress.Offset) handler.UploadProgress <- info return case <-time.After(1 * time.Second): info.Offset = atomic.LoadInt64(&progress.Offset) handler.UploadProgress <- info } } }() return reader, stop }
go
func (handler *UnroutedHandler) sendProgressMessages(info FileInfo, reader io.Reader) (io.Reader, chan<- struct{}) { progress := &progressWriter{ Offset: info.Offset, } stop := make(chan struct{}, 1) reader = io.TeeReader(reader, progress) go func() { for { select { case <-stop: info.Offset = atomic.LoadInt64(&progress.Offset) handler.UploadProgress <- info return case <-time.After(1 * time.Second): info.Offset = atomic.LoadInt64(&progress.Offset) handler.UploadProgress <- info } } }() return reader, stop }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "sendProgressMessages", "(", "info", "FileInfo", ",", "reader", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "chan", "<-", "struct", "{", "}", ")", "{", "progress", ":=", "&", "progressWriter", "{", "Offset", ":", "info", ".", "Offset", ",", "}", "\n", "stop", ":=", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", "\n", "reader", "=", "io", ".", "TeeReader", "(", "reader", ",", "progress", ")", "\n\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "stop", ":", "info", ".", "Offset", "=", "atomic", ".", "LoadInt64", "(", "&", "progress", ".", "Offset", ")", "\n", "handler", ".", "UploadProgress", "<-", "info", "\n", "return", "\n", "case", "<-", "time", ".", "After", "(", "1", "*", "time", ".", "Second", ")", ":", "info", ".", "Offset", "=", "atomic", ".", "LoadInt64", "(", "&", "progress", ".", "Offset", ")", "\n", "handler", ".", "UploadProgress", "<-", "info", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "reader", ",", "stop", "\n", "}" ]
// sendProgressMessage will send a notification over the UploadProgress channel // every second, indicating how much data has been transfered to the server. // It will stop sending these instances once the returned channel has been // closed. The returned reader should be used to read the request body.
[ "sendProgressMessage", "will", "send", "a", "notification", "over", "the", "UploadProgress", "channel", "every", "second", "indicating", "how", "much", "data", "has", "been", "transfered", "to", "the", "server", ".", "It", "will", "stop", "sending", "these", "instances", "once", "the", "returned", "channel", "has", "been", "closed", ".", "The", "returned", "reader", "should", "be", "used", "to", "read", "the", "request", "body", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L824-L846
train
tus/tusd
unrouted_handler.go
sizeOfUploads
func (handler *UnroutedHandler) sizeOfUploads(ids []string) (size int64, err error) { for _, id := range ids { info, err := handler.composer.Core.GetInfo(id) if err != nil { return size, err } if info.SizeIsDeferred || info.Offset != info.Size { err = ErrUploadNotFinished return size, err } size += info.Size } return }
go
func (handler *UnroutedHandler) sizeOfUploads(ids []string) (size int64, err error) { for _, id := range ids { info, err := handler.composer.Core.GetInfo(id) if err != nil { return size, err } if info.SizeIsDeferred || info.Offset != info.Size { err = ErrUploadNotFinished return size, err } size += info.Size } return }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "sizeOfUploads", "(", "ids", "[", "]", "string", ")", "(", "size", "int64", ",", "err", "error", ")", "{", "for", "_", ",", "id", ":=", "range", "ids", "{", "info", ",", "err", ":=", "handler", ".", "composer", ".", "Core", ".", "GetInfo", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "size", ",", "err", "\n", "}", "\n\n", "if", "info", ".", "SizeIsDeferred", "||", "info", ".", "Offset", "!=", "info", ".", "Size", "{", "err", "=", "ErrUploadNotFinished", "\n", "return", "size", ",", "err", "\n", "}", "\n\n", "size", "+=", "info", ".", "Size", "\n", "}", "\n\n", "return", "\n", "}" ]
// The get sum of all sizes for a list of upload ids while checking whether // all of these uploads are finished yet. This is used to calculate the size // of a final resource.
[ "The", "get", "sum", "of", "all", "sizes", "for", "a", "list", "of", "upload", "ids", "while", "checking", "whether", "all", "of", "these", "uploads", "are", "finished", "yet", ".", "This", "is", "used", "to", "calculate", "the", "size", "of", "a", "final", "resource", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L889-L905
train
tus/tusd
unrouted_handler.go
validateNewUploadLengthHeaders
func (handler *UnroutedHandler) validateNewUploadLengthHeaders(uploadLengthHeader string, uploadDeferLengthHeader string) (uploadLength int64, uploadLengthDeferred bool, err error) { haveBothLengthHeaders := uploadLengthHeader != "" && uploadDeferLengthHeader != "" haveInvalidDeferHeader := uploadDeferLengthHeader != "" && uploadDeferLengthHeader != UploadLengthDeferred lengthIsDeferred := uploadDeferLengthHeader == UploadLengthDeferred if lengthIsDeferred && !handler.composer.UsesLengthDeferrer { err = ErrNotImplemented } else if haveBothLengthHeaders { err = ErrUploadLengthAndUploadDeferLength } else if haveInvalidDeferHeader { err = ErrInvalidUploadDeferLength } else if lengthIsDeferred { uploadLengthDeferred = true } else { uploadLength, err = strconv.ParseInt(uploadLengthHeader, 10, 64) if err != nil || uploadLength < 0 { err = ErrInvalidUploadLength } } return }
go
func (handler *UnroutedHandler) validateNewUploadLengthHeaders(uploadLengthHeader string, uploadDeferLengthHeader string) (uploadLength int64, uploadLengthDeferred bool, err error) { haveBothLengthHeaders := uploadLengthHeader != "" && uploadDeferLengthHeader != "" haveInvalidDeferHeader := uploadDeferLengthHeader != "" && uploadDeferLengthHeader != UploadLengthDeferred lengthIsDeferred := uploadDeferLengthHeader == UploadLengthDeferred if lengthIsDeferred && !handler.composer.UsesLengthDeferrer { err = ErrNotImplemented } else if haveBothLengthHeaders { err = ErrUploadLengthAndUploadDeferLength } else if haveInvalidDeferHeader { err = ErrInvalidUploadDeferLength } else if lengthIsDeferred { uploadLengthDeferred = true } else { uploadLength, err = strconv.ParseInt(uploadLengthHeader, 10, 64) if err != nil || uploadLength < 0 { err = ErrInvalidUploadLength } } return }
[ "func", "(", "handler", "*", "UnroutedHandler", ")", "validateNewUploadLengthHeaders", "(", "uploadLengthHeader", "string", ",", "uploadDeferLengthHeader", "string", ")", "(", "uploadLength", "int64", ",", "uploadLengthDeferred", "bool", ",", "err", "error", ")", "{", "haveBothLengthHeaders", ":=", "uploadLengthHeader", "!=", "\"", "\"", "&&", "uploadDeferLengthHeader", "!=", "\"", "\"", "\n", "haveInvalidDeferHeader", ":=", "uploadDeferLengthHeader", "!=", "\"", "\"", "&&", "uploadDeferLengthHeader", "!=", "UploadLengthDeferred", "\n", "lengthIsDeferred", ":=", "uploadDeferLengthHeader", "==", "UploadLengthDeferred", "\n\n", "if", "lengthIsDeferred", "&&", "!", "handler", ".", "composer", ".", "UsesLengthDeferrer", "{", "err", "=", "ErrNotImplemented", "\n", "}", "else", "if", "haveBothLengthHeaders", "{", "err", "=", "ErrUploadLengthAndUploadDeferLength", "\n", "}", "else", "if", "haveInvalidDeferHeader", "{", "err", "=", "ErrInvalidUploadDeferLength", "\n", "}", "else", "if", "lengthIsDeferred", "{", "uploadLengthDeferred", "=", "true", "\n", "}", "else", "{", "uploadLength", ",", "err", "=", "strconv", ".", "ParseInt", "(", "uploadLengthHeader", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "||", "uploadLength", "<", "0", "{", "err", "=", "ErrInvalidUploadLength", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// Verify that the Upload-Length and Upload-Defer-Length headers are acceptable for creating a // new upload
[ "Verify", "that", "the", "Upload", "-", "Length", "and", "Upload", "-", "Defer", "-", "Length", "headers", "are", "acceptable", "for", "creating", "a", "new", "upload" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L909-L930
train
tus/tusd
unrouted_handler.go
extractIDFromPath
func extractIDFromPath(url string) (string, error) { result := reExtractFileID.FindStringSubmatch(url) if len(result) != 2 { return "", ErrNotFound } return result[1], nil }
go
func extractIDFromPath(url string) (string, error) { result := reExtractFileID.FindStringSubmatch(url) if len(result) != 2 { return "", ErrNotFound } return result[1], nil }
[ "func", "extractIDFromPath", "(", "url", "string", ")", "(", "string", ",", "error", ")", "{", "result", ":=", "reExtractFileID", ".", "FindStringSubmatch", "(", "url", ")", "\n", "if", "len", "(", "result", ")", "!=", "2", "{", "return", "\"", "\"", ",", "ErrNotFound", "\n", "}", "\n", "return", "result", "[", "1", "]", ",", "nil", "\n", "}" ]
// extractIDFromPath pulls the last segment from the url provided
[ "extractIDFromPath", "pulls", "the", "last", "segment", "from", "the", "url", "provided" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/unrouted_handler.go#L1023-L1029
train
tus/tusd
gcsstore/gcsservice.go
NewGCSService
func NewGCSService(filename string) (*GCSService, error) { ctx := context.Background() client, err := storage.NewClient(ctx, option.WithServiceAccountFile(filename)) if err != nil { return nil, err } service := &GCSService{ Client: client, } return service, nil }
go
func NewGCSService(filename string) (*GCSService, error) { ctx := context.Background() client, err := storage.NewClient(ctx, option.WithServiceAccountFile(filename)) if err != nil { return nil, err } service := &GCSService{ Client: client, } return service, nil }
[ "func", "NewGCSService", "(", "filename", "string", ")", "(", "*", "GCSService", ",", "error", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "client", ",", "err", ":=", "storage", ".", "NewClient", "(", "ctx", ",", "option", ".", "WithServiceAccountFile", "(", "filename", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "service", ":=", "&", "GCSService", "{", "Client", ":", "client", ",", "}", "\n\n", "return", "service", ",", "nil", "\n", "}" ]
// NewGCSService returns a GCSSerivce object given a GCloud service account file path.
[ "NewGCSService", "returns", "a", "GCSSerivce", "object", "given", "a", "GCloud", "service", "account", "file", "path", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L82-L94
train
tus/tusd
gcsstore/gcsservice.go
GetObjectSize
func (service *GCSService) GetObjectSize(ctx context.Context, params GCSObjectParams) (int64, error) { attrs, err := service.GetObjectAttrs(ctx, params) if err != nil { return 0, err } return attrs.Size, nil }
go
func (service *GCSService) GetObjectSize(ctx context.Context, params GCSObjectParams) (int64, error) { attrs, err := service.GetObjectAttrs(ctx, params) if err != nil { return 0, err } return attrs.Size, nil }
[ "func", "(", "service", "*", "GCSService", ")", "GetObjectSize", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ")", "(", "int64", ",", "error", ")", "{", "attrs", ",", "err", ":=", "service", ".", "GetObjectAttrs", "(", "ctx", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "attrs", ".", "Size", ",", "nil", "\n", "}" ]
// GetObjectSize returns the byte length of the specified GCS object.
[ "GetObjectSize", "returns", "the", "byte", "length", "of", "the", "specified", "GCS", "object", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L97-L104
train
tus/tusd
gcsstore/gcsservice.go
DeleteObjectsWithFilter
func (service *GCSService) DeleteObjectsWithFilter(ctx context.Context, params GCSFilterParams) error { names, err := service.FilterObjects(ctx, params) if err != nil { return err } var objectParams GCSObjectParams for _, name := range names { objectParams = GCSObjectParams{ Bucket: params.Bucket, ID: name, } err := service.DeleteObject(ctx, objectParams) if err != nil { return err } } return nil }
go
func (service *GCSService) DeleteObjectsWithFilter(ctx context.Context, params GCSFilterParams) error { names, err := service.FilterObjects(ctx, params) if err != nil { return err } var objectParams GCSObjectParams for _, name := range names { objectParams = GCSObjectParams{ Bucket: params.Bucket, ID: name, } err := service.DeleteObject(ctx, objectParams) if err != nil { return err } } return nil }
[ "func", "(", "service", "*", "GCSService", ")", "DeleteObjectsWithFilter", "(", "ctx", "context", ".", "Context", ",", "params", "GCSFilterParams", ")", "error", "{", "names", ",", "err", ":=", "service", ".", "FilterObjects", "(", "ctx", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "objectParams", "GCSObjectParams", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "objectParams", "=", "GCSObjectParams", "{", "Bucket", ":", "params", ".", "Bucket", ",", "ID", ":", "name", ",", "}", "\n\n", "err", ":=", "service", ".", "DeleteObject", "(", "ctx", ",", "objectParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// DeleteObjectWithPrefix will delete objects who match the provided filter parameters.
[ "DeleteObjectWithPrefix", "will", "delete", "objects", "who", "match", "the", "provided", "filter", "parameters", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L107-L127
train
tus/tusd
gcsstore/gcsservice.go
compose
func (service *GCSService) compose(ctx context.Context, bucket string, srcs []string, dst string) error { dstParams := GCSObjectParams{ Bucket: bucket, ID: dst, } objSrcs := make([]*storage.ObjectHandle, len(srcs)) var crc uint32 for i := 0; i < len(srcs); i++ { objSrcs[i] = service.Client.Bucket(bucket).Object(srcs[i]) srcAttrs, err := service.GetObjectAttrs(ctx, GCSObjectParams{ Bucket: bucket, ID: srcs[i], }) if err != nil { return err } if i == 0 { crc = srcAttrs.CRC32C } else { crc = crc32combine.CRC32Combine(crc32.Castagnoli, crc, srcAttrs.CRC32C, srcAttrs.Size) } } attrs, err := service.GetObjectAttrs(ctx, GCSObjectParams{ Bucket: bucket, ID: srcs[0], }) if err != nil { return err } for i := 0; i < COMPOSE_RETRIES; i++ { dstCRC, err := service.ComposeFrom(ctx, objSrcs, dstParams, attrs.ContentType) if err != nil { return err } if dstCRC == crc { return nil } } err = service.DeleteObject(ctx, GCSObjectParams{ Bucket: bucket, ID: dst, }) if err != nil { return err } err = errors.New("GCS compose failed: Mismatch of CRC32 checksums") return err }
go
func (service *GCSService) compose(ctx context.Context, bucket string, srcs []string, dst string) error { dstParams := GCSObjectParams{ Bucket: bucket, ID: dst, } objSrcs := make([]*storage.ObjectHandle, len(srcs)) var crc uint32 for i := 0; i < len(srcs); i++ { objSrcs[i] = service.Client.Bucket(bucket).Object(srcs[i]) srcAttrs, err := service.GetObjectAttrs(ctx, GCSObjectParams{ Bucket: bucket, ID: srcs[i], }) if err != nil { return err } if i == 0 { crc = srcAttrs.CRC32C } else { crc = crc32combine.CRC32Combine(crc32.Castagnoli, crc, srcAttrs.CRC32C, srcAttrs.Size) } } attrs, err := service.GetObjectAttrs(ctx, GCSObjectParams{ Bucket: bucket, ID: srcs[0], }) if err != nil { return err } for i := 0; i < COMPOSE_RETRIES; i++ { dstCRC, err := service.ComposeFrom(ctx, objSrcs, dstParams, attrs.ContentType) if err != nil { return err } if dstCRC == crc { return nil } } err = service.DeleteObject(ctx, GCSObjectParams{ Bucket: bucket, ID: dst, }) if err != nil { return err } err = errors.New("GCS compose failed: Mismatch of CRC32 checksums") return err }
[ "func", "(", "service", "*", "GCSService", ")", "compose", "(", "ctx", "context", ".", "Context", ",", "bucket", "string", ",", "srcs", "[", "]", "string", ",", "dst", "string", ")", "error", "{", "dstParams", ":=", "GCSObjectParams", "{", "Bucket", ":", "bucket", ",", "ID", ":", "dst", ",", "}", "\n", "objSrcs", ":=", "make", "(", "[", "]", "*", "storage", ".", "ObjectHandle", ",", "len", "(", "srcs", ")", ")", "\n", "var", "crc", "uint32", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "srcs", ")", ";", "i", "++", "{", "objSrcs", "[", "i", "]", "=", "service", ".", "Client", ".", "Bucket", "(", "bucket", ")", ".", "Object", "(", "srcs", "[", "i", "]", ")", "\n", "srcAttrs", ",", "err", ":=", "service", ".", "GetObjectAttrs", "(", "ctx", ",", "GCSObjectParams", "{", "Bucket", ":", "bucket", ",", "ID", ":", "srcs", "[", "i", "]", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "i", "==", "0", "{", "crc", "=", "srcAttrs", ".", "CRC32C", "\n", "}", "else", "{", "crc", "=", "crc32combine", ".", "CRC32Combine", "(", "crc32", ".", "Castagnoli", ",", "crc", ",", "srcAttrs", ".", "CRC32C", ",", "srcAttrs", ".", "Size", ")", "\n", "}", "\n", "}", "\n\n", "attrs", ",", "err", ":=", "service", ".", "GetObjectAttrs", "(", "ctx", ",", "GCSObjectParams", "{", "Bucket", ":", "bucket", ",", "ID", ":", "srcs", "[", "0", "]", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "COMPOSE_RETRIES", ";", "i", "++", "{", "dstCRC", ",", "err", ":=", "service", ".", "ComposeFrom", "(", "ctx", ",", "objSrcs", ",", "dstParams", ",", "attrs", ".", "ContentType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "dstCRC", "==", "crc", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "err", "=", "service", ".", "DeleteObject", "(", "ctx", ",", "GCSObjectParams", "{", "Bucket", ":", "bucket", ",", "ID", ":", "dst", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "err", "\n", "}" ]
// Compose takes a bucket name, a list of initial source names, and a destination string to compose multiple GCS objects together
[ "Compose", "takes", "a", "bucket", "name", "a", "list", "of", "initial", "source", "names", "and", "a", "destination", "string", "to", "compose", "multiple", "GCS", "objects", "together" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L132-L186
train
tus/tusd
gcsstore/gcsservice.go
ComposeObjects
func (service *GCSService) ComposeObjects(ctx context.Context, params GCSComposeParams) error { err := service.recursiveCompose(ctx, params.Sources, params, 0) if err != nil { return err } return nil }
go
func (service *GCSService) ComposeObjects(ctx context.Context, params GCSComposeParams) error { err := service.recursiveCompose(ctx, params.Sources, params, 0) if err != nil { return err } return nil }
[ "func", "(", "service", "*", "GCSService", ")", "ComposeObjects", "(", "ctx", "context", ".", "Context", ",", "params", "GCSComposeParams", ")", "error", "{", "err", ":=", "service", ".", "recursiveCompose", "(", "ctx", ",", "params", ".", "Sources", ",", "params", ",", "0", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ComposeObjects composes multiple GCS objects in to a single object. // Since GCS limits composition to a max of 32 objects, additional logic // has been added to chunk objects in to groups of 32 and then recursively // compose those objects together.
[ "ComposeObjects", "composes", "multiple", "GCS", "objects", "in", "to", "a", "single", "object", ".", "Since", "GCS", "limits", "composition", "to", "a", "max", "of", "32", "objects", "additional", "logic", "has", "been", "added", "to", "chunk", "objects", "in", "to", "groups", "of", "32", "and", "then", "recursively", "compose", "those", "objects", "together", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L240-L248
train
tus/tusd
gcsstore/gcsservice.go
ReadObject
func (service *GCSService) ReadObject(ctx context.Context, params GCSObjectParams) (GCSReader, error) { r, err := service.Client.Bucket(params.Bucket).Object(params.ID).NewReader(ctx) if err != nil { return nil, err } return r, nil }
go
func (service *GCSService) ReadObject(ctx context.Context, params GCSObjectParams) (GCSReader, error) { r, err := service.Client.Bucket(params.Bucket).Object(params.ID).NewReader(ctx) if err != nil { return nil, err } return r, nil }
[ "func", "(", "service", "*", "GCSService", ")", "ReadObject", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ")", "(", "GCSReader", ",", "error", ")", "{", "r", ",", "err", ":=", "service", ".", "Client", ".", "Bucket", "(", "params", ".", "Bucket", ")", ".", "Object", "(", "params", ".", "ID", ")", ".", "NewReader", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "r", ",", "nil", "\n", "}" ]
// ReadObject reads a GCSObjectParams, returning a GCSReader object if successful, and an error otherwise
[ "ReadObject", "reads", "a", "GCSObjectParams", "returning", "a", "GCSReader", "object", "if", "successful", "and", "an", "error", "otherwise" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L264-L271
train
tus/tusd
gcsstore/gcsservice.go
SetObjectMetadata
func (service *GCSService) SetObjectMetadata(ctx context.Context, params GCSObjectParams, metadata map[string]string) error { attrs := storage.ObjectAttrsToUpdate{ Metadata: metadata, } _, err := service.Client.Bucket(params.Bucket).Object(params.ID).Update(ctx, attrs) return err }
go
func (service *GCSService) SetObjectMetadata(ctx context.Context, params GCSObjectParams, metadata map[string]string) error { attrs := storage.ObjectAttrsToUpdate{ Metadata: metadata, } _, err := service.Client.Bucket(params.Bucket).Object(params.ID).Update(ctx, attrs) return err }
[ "func", "(", "service", "*", "GCSService", ")", "SetObjectMetadata", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ",", "metadata", "map", "[", "string", "]", "string", ")", "error", "{", "attrs", ":=", "storage", ".", "ObjectAttrsToUpdate", "{", "Metadata", ":", "metadata", ",", "}", "\n", "_", ",", "err", ":=", "service", ".", "Client", ".", "Bucket", "(", "params", ".", "Bucket", ")", ".", "Object", "(", "params", ".", "ID", ")", ".", "Update", "(", "ctx", ",", "attrs", ")", "\n\n", "return", "err", "\n", "}" ]
// SetObjectMetadata reads a GCSObjectParams and a map of metedata, returning a nil on sucess and an error otherwise
[ "SetObjectMetadata", "reads", "a", "GCSObjectParams", "and", "a", "map", "of", "metedata", "returning", "a", "nil", "on", "sucess", "and", "an", "error", "otherwise" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L274-L281
train
tus/tusd
gcsstore/gcsservice.go
DeleteObject
func (service *GCSService) DeleteObject(ctx context.Context, params GCSObjectParams) error { return service.Client.Bucket(params.Bucket).Object(params.ID).Delete(ctx) }
go
func (service *GCSService) DeleteObject(ctx context.Context, params GCSObjectParams) error { return service.Client.Bucket(params.Bucket).Object(params.ID).Delete(ctx) }
[ "func", "(", "service", "*", "GCSService", ")", "DeleteObject", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ")", "error", "{", "return", "service", ".", "Client", ".", "Bucket", "(", "params", ".", "Bucket", ")", ".", "Object", "(", "params", ".", "ID", ")", ".", "Delete", "(", "ctx", ")", "\n", "}" ]
// DeleteObject deletes the object defined by GCSObjectParams
[ "DeleteObject", "deletes", "the", "object", "defined", "by", "GCSObjectParams" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L284-L286
train
tus/tusd
gcsstore/gcsservice.go
WriteObject
func (service *GCSService) WriteObject(ctx context.Context, params GCSObjectParams, r io.Reader) (int64, error) { obj := service.Client.Bucket(params.Bucket).Object(params.ID) w := obj.NewWriter(ctx) n, err := io.Copy(w, r) if err != nil { return 0, err } err = w.Close() if err != nil { if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == 404 { return 0, fmt.Errorf("gcsstore: the bucket %s could not be found while trying to write an object", params.Bucket) } return 0, err } return n, err }
go
func (service *GCSService) WriteObject(ctx context.Context, params GCSObjectParams, r io.Reader) (int64, error) { obj := service.Client.Bucket(params.Bucket).Object(params.ID) w := obj.NewWriter(ctx) n, err := io.Copy(w, r) if err != nil { return 0, err } err = w.Close() if err != nil { if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == 404 { return 0, fmt.Errorf("gcsstore: the bucket %s could not be found while trying to write an object", params.Bucket) } return 0, err } return n, err }
[ "func", "(", "service", "*", "GCSService", ")", "WriteObject", "(", "ctx", "context", ".", "Context", ",", "params", "GCSObjectParams", ",", "r", "io", ".", "Reader", ")", "(", "int64", ",", "error", ")", "{", "obj", ":=", "service", ".", "Client", ".", "Bucket", "(", "params", ".", "Bucket", ")", ".", "Object", "(", "params", ".", "ID", ")", "\n\n", "w", ":=", "obj", ".", "NewWriter", "(", "ctx", ")", "\n\n", "n", ",", "err", ":=", "io", ".", "Copy", "(", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "err", "=", "w", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "gErr", ",", "ok", ":=", "err", ".", "(", "*", "googleapi", ".", "Error", ")", ";", "ok", "&&", "gErr", ".", "Code", "==", "404", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "params", ".", "Bucket", ")", "\n", "}", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "n", ",", "err", "\n", "}" ]
// Write object writes the file set out by the GCSObjectParams
[ "Write", "object", "writes", "the", "file", "set", "out", "by", "the", "GCSObjectParams" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L289-L308
train
tus/tusd
gcsstore/gcsservice.go
ComposeFrom
func (service *GCSService) ComposeFrom(ctx context.Context, objSrcs []*storage.ObjectHandle, dstParams GCSObjectParams, contentType string) (uint32, error) { dstObj := service.Client.Bucket(dstParams.Bucket).Object(dstParams.ID) c := dstObj.ComposerFrom(objSrcs...) c.ContentType = contentType _, err := c.Run(ctx) if err != nil { return 0, err } dstAttrs, err := dstObj.Attrs(ctx) if err != nil { return 0, err } return dstAttrs.CRC32C, nil }
go
func (service *GCSService) ComposeFrom(ctx context.Context, objSrcs []*storage.ObjectHandle, dstParams GCSObjectParams, contentType string) (uint32, error) { dstObj := service.Client.Bucket(dstParams.Bucket).Object(dstParams.ID) c := dstObj.ComposerFrom(objSrcs...) c.ContentType = contentType _, err := c.Run(ctx) if err != nil { return 0, err } dstAttrs, err := dstObj.Attrs(ctx) if err != nil { return 0, err } return dstAttrs.CRC32C, nil }
[ "func", "(", "service", "*", "GCSService", ")", "ComposeFrom", "(", "ctx", "context", ".", "Context", ",", "objSrcs", "[", "]", "*", "storage", ".", "ObjectHandle", ",", "dstParams", "GCSObjectParams", ",", "contentType", "string", ")", "(", "uint32", ",", "error", ")", "{", "dstObj", ":=", "service", ".", "Client", ".", "Bucket", "(", "dstParams", ".", "Bucket", ")", ".", "Object", "(", "dstParams", ".", "ID", ")", "\n", "c", ":=", "dstObj", ".", "ComposerFrom", "(", "objSrcs", "...", ")", "\n", "c", ".", "ContentType", "=", "contentType", "\n", "_", ",", "err", ":=", "c", ".", "Run", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "dstAttrs", ",", "err", ":=", "dstObj", ".", "Attrs", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "dstAttrs", ".", "CRC32C", ",", "nil", "\n", "}" ]
// ComposeFrom composes multiple object types together,
[ "ComposeFrom", "composes", "multiple", "object", "types", "together" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsservice.go#L311-L326
train
tus/tusd
memorylocker/memorylocker.go
UnlockUpload
func (locker *MemoryLocker) UnlockUpload(id string) error { locker.mutex.Lock() // Deleting a non-existing key does not end in unexpected errors or panic // since this operation results in a no-op delete(locker.locks, id) locker.mutex.Unlock() return nil }
go
func (locker *MemoryLocker) UnlockUpload(id string) error { locker.mutex.Lock() // Deleting a non-existing key does not end in unexpected errors or panic // since this operation results in a no-op delete(locker.locks, id) locker.mutex.Unlock() return nil }
[ "func", "(", "locker", "*", "MemoryLocker", ")", "UnlockUpload", "(", "id", "string", ")", "error", "{", "locker", ".", "mutex", ".", "Lock", "(", ")", "\n\n", "// Deleting a non-existing key does not end in unexpected errors or panic", "// since this operation results in a no-op", "delete", "(", "locker", ".", "locks", ",", "id", ")", "\n\n", "locker", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// UnlockUpload releases a lock. If no such lock exists, no error will be returned.
[ "UnlockUpload", "releases", "a", "lock", ".", "If", "no", "such", "lock", "exists", "no", "error", "will", "be", "returned", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/memorylocker/memorylocker.go#L62-L71
train
tus/tusd
gcsstore/gcsstore.go
New
func New(bucket string, service GCSAPI) GCSStore { return GCSStore{ Bucket: bucket, Service: service, } }
go
func New(bucket string, service GCSAPI) GCSStore { return GCSStore{ Bucket: bucket, Service: service, } }
[ "func", "New", "(", "bucket", "string", ",", "service", "GCSAPI", ")", "GCSStore", "{", "return", "GCSStore", "{", "Bucket", ":", "bucket", ",", "Service", ":", "service", ",", "}", "\n", "}" ]
// New constructs a new GCS storage backend using the supplied GCS bucket name // and service object.
[ "New", "constructs", "a", "new", "GCS", "storage", "backend", "using", "the", "supplied", "GCS", "bucket", "name", "and", "service", "object", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/gcsstore/gcsstore.go#L42-L47
train
tus/tusd
etcd3locker/locker.go
NewWithPrefix
func NewWithPrefix(client *etcd3.Client, prefix string) (*Etcd3Locker, error) { lockerOptions := DefaultLockerOptions() lockerOptions.SetPrefix(prefix) return NewWithLockerOptions(client, lockerOptions) }
go
func NewWithPrefix(client *etcd3.Client, prefix string) (*Etcd3Locker, error) { lockerOptions := DefaultLockerOptions() lockerOptions.SetPrefix(prefix) return NewWithLockerOptions(client, lockerOptions) }
[ "func", "NewWithPrefix", "(", "client", "*", "etcd3", ".", "Client", ",", "prefix", "string", ")", "(", "*", "Etcd3Locker", ",", "error", ")", "{", "lockerOptions", ":=", "DefaultLockerOptions", "(", ")", "\n", "lockerOptions", ".", "SetPrefix", "(", "prefix", ")", "\n", "return", "NewWithLockerOptions", "(", "client", ",", "lockerOptions", ")", "\n", "}" ]
// This method may be used if a different prefix is required for multi-tenant etcd clusters
[ "This", "method", "may", "be", "used", "if", "a", "different", "prefix", "is", "required", "for", "multi", "-", "tenant", "etcd", "clusters" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/etcd3locker/locker.go#L79-L83
train
tus/tusd
composer.go
newStoreComposerFromDataStore
func newStoreComposerFromDataStore(store DataStore) *StoreComposer { composer := NewStoreComposer() composer.UseCore(store) if mod, ok := store.(TerminaterDataStore); ok { composer.UseTerminater(mod) } if mod, ok := store.(FinisherDataStore); ok { composer.UseFinisher(mod) } if mod, ok := store.(LockerDataStore); ok { composer.UseLocker(mod) } if mod, ok := store.(GetReaderDataStore); ok { composer.UseGetReader(mod) } if mod, ok := store.(ConcaterDataStore); ok { composer.UseConcater(mod) } if mod, ok := store.(LengthDeferrerDataStore); ok { composer.UseLengthDeferrer(mod) } return composer }
go
func newStoreComposerFromDataStore(store DataStore) *StoreComposer { composer := NewStoreComposer() composer.UseCore(store) if mod, ok := store.(TerminaterDataStore); ok { composer.UseTerminater(mod) } if mod, ok := store.(FinisherDataStore); ok { composer.UseFinisher(mod) } if mod, ok := store.(LockerDataStore); ok { composer.UseLocker(mod) } if mod, ok := store.(GetReaderDataStore); ok { composer.UseGetReader(mod) } if mod, ok := store.(ConcaterDataStore); ok { composer.UseConcater(mod) } if mod, ok := store.(LengthDeferrerDataStore); ok { composer.UseLengthDeferrer(mod) } return composer }
[ "func", "newStoreComposerFromDataStore", "(", "store", "DataStore", ")", "*", "StoreComposer", "{", "composer", ":=", "NewStoreComposer", "(", ")", "\n", "composer", ".", "UseCore", "(", "store", ")", "\n\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "TerminaterDataStore", ")", ";", "ok", "{", "composer", ".", "UseTerminater", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "FinisherDataStore", ")", ";", "ok", "{", "composer", ".", "UseFinisher", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "LockerDataStore", ")", ";", "ok", "{", "composer", ".", "UseLocker", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "GetReaderDataStore", ")", ";", "ok", "{", "composer", ".", "UseGetReader", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "ConcaterDataStore", ")", ";", "ok", "{", "composer", ".", "UseConcater", "(", "mod", ")", "\n", "}", "\n", "if", "mod", ",", "ok", ":=", "store", ".", "(", "LengthDeferrerDataStore", ")", ";", "ok", "{", "composer", ".", "UseLengthDeferrer", "(", "mod", ")", "\n", "}", "\n\n", "return", "composer", "\n", "}" ]
// newStoreComposerFromDataStore creates a new store composer and attempts to // extract the extensions for the provided store. This is intended to be used // for transitioning from data stores to composers.
[ "newStoreComposerFromDataStore", "creates", "a", "new", "store", "composer", "and", "attempts", "to", "extract", "the", "extensions", "for", "the", "provided", "store", ".", "This", "is", "intended", "to", "be", "used", "for", "transitioning", "from", "data", "stores", "to", "composers", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/composer.go#L31-L55
train
tus/tusd
composer.go
Capabilities
func (store *StoreComposer) Capabilities() string { str := "Core: " if store.Core != nil { str += "✓" } else { str += "✗" } str += ` Terminater: ` if store.UsesTerminater { str += "✓" } else { str += "✗" } str += ` Finisher: ` if store.UsesFinisher { str += "✓" } else { str += "✗" } str += ` Locker: ` if store.UsesLocker { str += "✓" } else { str += "✗" } str += ` GetReader: ` if store.UsesGetReader { str += "✓" } else { str += "✗" } str += ` Concater: ` if store.UsesConcater { str += "✓" } else { str += "✗" } str += ` LengthDeferrer: ` if store.UsesLengthDeferrer { str += "✓" } else { str += "✗" } return str }
go
func (store *StoreComposer) Capabilities() string { str := "Core: " if store.Core != nil { str += "✓" } else { str += "✗" } str += ` Terminater: ` if store.UsesTerminater { str += "✓" } else { str += "✗" } str += ` Finisher: ` if store.UsesFinisher { str += "✓" } else { str += "✗" } str += ` Locker: ` if store.UsesLocker { str += "✓" } else { str += "✗" } str += ` GetReader: ` if store.UsesGetReader { str += "✓" } else { str += "✗" } str += ` Concater: ` if store.UsesConcater { str += "✓" } else { str += "✗" } str += ` LengthDeferrer: ` if store.UsesLengthDeferrer { str += "✓" } else { str += "✗" } return str }
[ "func", "(", "store", "*", "StoreComposer", ")", "Capabilities", "(", ")", "string", "{", "str", ":=", "\"", "\"", "\n\n", "if", "store", ".", "Core", "!=", "nil", "{", "str", "+=", "\"", "", "\n", "}", "else", "{", "str", "+=", "\"", "", "\n", "}", "\n\n", "str", "+=", "` Terminater: `", "\n", "if", "store", ".", "UsesTerminater", "{", "str", "+=", "\"", "", "\n", "}", "else", "{", "str", "+=", "\"", "", "\n", "}", "\n", "str", "+=", "` Finisher: `", "\n", "if", "store", ".", "UsesFinisher", "{", "str", "+=", "\"", "", "\n", "}", "else", "{", "str", "+=", "\"", "", "\n", "}", "\n", "str", "+=", "` Locker: `", "\n", "if", "store", ".", "UsesLocker", "{", "str", "+=", "\"", "", "\n", "}", "else", "{", "str", "+=", "\"", "", "\n", "}", "\n", "str", "+=", "` GetReader: `", "\n", "if", "store", ".", "UsesGetReader", "{", "str", "+=", "\"", "", "\n", "}", "else", "{", "str", "+=", "\"", "", "\n", "}", "\n", "str", "+=", "` Concater: `", "\n", "if", "store", ".", "UsesConcater", "{", "str", "+=", "\"", "", "\n", "}", "else", "{", "str", "+=", "\"", "", "\n", "}", "\n", "str", "+=", "` LengthDeferrer: `", "\n", "if", "store", ".", "UsesLengthDeferrer", "{", "str", "+=", "\"", "", "\n", "}", "else", "{", "str", "+=", "\"", "", "\n", "}", "\n\n", "return", "str", "\n", "}" ]
// Capabilities returns a string representing the provided extensions in a // human-readable format meant for debugging.
[ "Capabilities", "returns", "a", "string", "representing", "the", "provided", "extensions", "in", "a", "human", "-", "readable", "format", "meant", "for", "debugging", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/composer.go#L59-L106
train
tus/tusd
s3store/s3store.go
New
func New(bucket string, service S3API) S3Store { return S3Store{ Bucket: bucket, Service: service, MaxPartSize: 5 * 1024 * 1024 * 1024, MinPartSize: 5 * 1024 * 1024, MaxMultipartParts: 10000, MaxObjectSize: 5 * 1024 * 1024 * 1024 * 1024, } }
go
func New(bucket string, service S3API) S3Store { return S3Store{ Bucket: bucket, Service: service, MaxPartSize: 5 * 1024 * 1024 * 1024, MinPartSize: 5 * 1024 * 1024, MaxMultipartParts: 10000, MaxObjectSize: 5 * 1024 * 1024 * 1024 * 1024, } }
[ "func", "New", "(", "bucket", "string", ",", "service", "S3API", ")", "S3Store", "{", "return", "S3Store", "{", "Bucket", ":", "bucket", ",", "Service", ":", "service", ",", "MaxPartSize", ":", "5", "*", "1024", "*", "1024", "*", "1024", ",", "MinPartSize", ":", "5", "*", "1024", "*", "1024", ",", "MaxMultipartParts", ":", "10000", ",", "MaxObjectSize", ":", "5", "*", "1024", "*", "1024", "*", "1024", "*", "1024", ",", "}", "\n", "}" ]
// New constructs a new storage using the supplied bucket and service object.
[ "New", "constructs", "a", "new", "storage", "using", "the", "supplied", "bucket", "and", "service", "object", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/s3store/s3store.go#L147-L156
train
tus/tusd
s3store/s3store.go
isAwsError
func isAwsError(err error, code string) bool { if err, ok := err.(awserr.Error); ok && err.Code() == code { return true } return false }
go
func isAwsError(err error, code string) bool { if err, ok := err.(awserr.Error); ok && err.Code() == code { return true } return false }
[ "func", "isAwsError", "(", "err", "error", ",", "code", "string", ")", "bool", "{", "if", "err", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "&&", "err", ".", "Code", "(", ")", "==", "code", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isAwsError tests whether an error object is an instance of the AWS error // specified by its code.
[ "isAwsError", "tests", "whether", "an", "error", "object", "is", "an", "instance", "of", "the", "AWS", "error", "specified", "by", "its", "code", "." ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/s3store/s3store.go#L676-L681
train
tus/tusd
etcd3locker/lock.go
Acquire
func (lock *etcd3Lock) Acquire() error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // this is a blocking call; if we receive DeadlineExceeded // the lock is most likely already taken if err := lock.Mutex.Lock(ctx); err != nil { if err == context.DeadlineExceeded { return tusd.ErrFileLocked } else { return err } } return nil }
go
func (lock *etcd3Lock) Acquire() error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // this is a blocking call; if we receive DeadlineExceeded // the lock is most likely already taken if err := lock.Mutex.Lock(ctx); err != nil { if err == context.DeadlineExceeded { return tusd.ErrFileLocked } else { return err } } return nil }
[ "func", "(", "lock", "*", "etcd3Lock", ")", "Acquire", "(", ")", "error", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "5", "*", "time", ".", "Second", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "// this is a blocking call; if we receive DeadlineExceeded", "// the lock is most likely already taken", "if", "err", ":=", "lock", ".", "Mutex", ".", "Lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "context", ".", "DeadlineExceeded", "{", "return", "tusd", ".", "ErrFileLocked", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Acquires a lock from etcd3
[ "Acquires", "a", "lock", "from", "etcd3" ]
12f102abf6cbd174b4dc9323672f59c6357b561c
https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/etcd3locker/lock.go#L27-L41
train
mitchellh/mapstructure
decode_hooks.go
DecodeHookExec
func DecodeHookExec( raw DecodeHookFunc, from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) { switch f := typedDecodeHook(raw).(type) { case DecodeHookFuncType: return f(from, to, data) case DecodeHookFuncKind: return f(from.Kind(), to.Kind(), data) default: return nil, errors.New("invalid decode hook signature") } }
go
func DecodeHookExec( raw DecodeHookFunc, from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) { switch f := typedDecodeHook(raw).(type) { case DecodeHookFuncType: return f(from, to, data) case DecodeHookFuncKind: return f(from.Kind(), to.Kind(), data) default: return nil, errors.New("invalid decode hook signature") } }
[ "func", "DecodeHookExec", "(", "raw", "DecodeHookFunc", ",", "from", "reflect", ".", "Type", ",", "to", "reflect", ".", "Type", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "switch", "f", ":=", "typedDecodeHook", "(", "raw", ")", ".", "(", "type", ")", "{", "case", "DecodeHookFuncType", ":", "return", "f", "(", "from", ",", "to", ",", "data", ")", "\n", "case", "DecodeHookFuncKind", ":", "return", "f", "(", "from", ".", "Kind", "(", ")", ",", "to", ".", "Kind", "(", ")", ",", "data", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// DecodeHookExec executes the given decode hook. This should be used // since it'll naturally degrade to the older backwards compatible DecodeHookFunc // that took reflect.Kind instead of reflect.Type.
[ "DecodeHookExec", "executes", "the", "given", "decode", "hook", ".", "This", "should", "be", "used", "since", "it", "ll", "naturally", "degrade", "to", "the", "older", "backwards", "compatible", "DecodeHookFunc", "that", "took", "reflect", ".", "Kind", "instead", "of", "reflect", ".", "Type", "." ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L39-L51
train
mitchellh/mapstructure
decode_hooks.go
ComposeDecodeHookFunc
func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { var err error for _, f1 := range fs { data, err = DecodeHookExec(f1, f, t, data) if err != nil { return nil, err } // Modify the from kind to be correct with the new data f = nil if val := reflect.ValueOf(data); val.IsValid() { f = val.Type() } } return data, nil } }
go
func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { var err error for _, f1 := range fs { data, err = DecodeHookExec(f1, f, t, data) if err != nil { return nil, err } // Modify the from kind to be correct with the new data f = nil if val := reflect.ValueOf(data); val.IsValid() { f = val.Type() } } return data, nil } }
[ "func", "ComposeDecodeHookFunc", "(", "fs", "...", "DecodeHookFunc", ")", "DecodeHookFunc", "{", "return", "func", "(", "f", "reflect", ".", "Type", ",", "t", "reflect", ".", "Type", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "err", "error", "\n", "for", "_", ",", "f1", ":=", "range", "fs", "{", "data", ",", "err", "=", "DecodeHookExec", "(", "f1", ",", "f", ",", "t", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Modify the from kind to be correct with the new data", "f", "=", "nil", "\n", "if", "val", ":=", "reflect", ".", "ValueOf", "(", "data", ")", ";", "val", ".", "IsValid", "(", ")", "{", "f", "=", "val", ".", "Type", "(", ")", "\n", "}", "\n", "}", "\n\n", "return", "data", ",", "nil", "\n", "}", "\n", "}" ]
// ComposeDecodeHookFunc creates a single DecodeHookFunc that // automatically composes multiple DecodeHookFuncs. // // The composed funcs are called in order, with the result of the // previous transformation.
[ "ComposeDecodeHookFunc", "creates", "a", "single", "DecodeHookFunc", "that", "automatically", "composes", "multiple", "DecodeHookFuncs", ".", "The", "composed", "funcs", "are", "called", "in", "order", "with", "the", "result", "of", "the", "previous", "transformation", "." ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L58-L79
train
mitchellh/mapstructure
decode_hooks.go
StringToTimeDurationHookFunc
func StringToTimeDurationHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(time.Duration(5)) { return data, nil } // Convert it by parsing return time.ParseDuration(data.(string)) } }
go
func StringToTimeDurationHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(time.Duration(5)) { return data, nil } // Convert it by parsing return time.ParseDuration(data.(string)) } }
[ "func", "StringToTimeDurationHookFunc", "(", ")", "DecodeHookFunc", "{", "return", "func", "(", "f", "reflect", ".", "Type", ",", "t", "reflect", ".", "Type", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "f", ".", "Kind", "(", ")", "!=", "reflect", ".", "String", "{", "return", "data", ",", "nil", "\n", "}", "\n", "if", "t", "!=", "reflect", ".", "TypeOf", "(", "time", ".", "Duration", "(", "5", ")", ")", "{", "return", "data", ",", "nil", "\n", "}", "\n\n", "// Convert it by parsing", "return", "time", ".", "ParseDuration", "(", "data", ".", "(", "string", ")", ")", "\n", "}", "\n", "}" ]
// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts // strings to time.Duration.
[ "StringToTimeDurationHookFunc", "returns", "a", "DecodeHookFunc", "that", "converts", "strings", "to", "time", ".", "Duration", "." ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L103-L118
train
mitchellh/mapstructure
decode_hooks.go
StringToIPHookFunc
func StringToIPHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(net.IP{}) { return data, nil } // Convert it by parsing ip := net.ParseIP(data.(string)) if ip == nil { return net.IP{}, fmt.Errorf("failed parsing ip %v", data) } return ip, nil } }
go
func StringToIPHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(net.IP{}) { return data, nil } // Convert it by parsing ip := net.ParseIP(data.(string)) if ip == nil { return net.IP{}, fmt.Errorf("failed parsing ip %v", data) } return ip, nil } }
[ "func", "StringToIPHookFunc", "(", ")", "DecodeHookFunc", "{", "return", "func", "(", "f", "reflect", ".", "Type", ",", "t", "reflect", ".", "Type", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "f", ".", "Kind", "(", ")", "!=", "reflect", ".", "String", "{", "return", "data", ",", "nil", "\n", "}", "\n", "if", "t", "!=", "reflect", ".", "TypeOf", "(", "net", ".", "IP", "{", "}", ")", "{", "return", "data", ",", "nil", "\n", "}", "\n\n", "// Convert it by parsing", "ip", ":=", "net", ".", "ParseIP", "(", "data", ".", "(", "string", ")", ")", "\n", "if", "ip", "==", "nil", "{", "return", "net", ".", "IP", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "data", ")", "\n", "}", "\n\n", "return", "ip", ",", "nil", "\n", "}", "\n", "}" ]
// StringToIPHookFunc returns a DecodeHookFunc that converts // strings to net.IP
[ "StringToIPHookFunc", "returns", "a", "DecodeHookFunc", "that", "converts", "strings", "to", "net", ".", "IP" ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L122-L142
train
mitchellh/mapstructure
decode_hooks.go
StringToIPNetHookFunc
func StringToIPNetHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(net.IPNet{}) { return data, nil } // Convert it by parsing _, net, err := net.ParseCIDR(data.(string)) return net, err } }
go
func StringToIPNetHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(net.IPNet{}) { return data, nil } // Convert it by parsing _, net, err := net.ParseCIDR(data.(string)) return net, err } }
[ "func", "StringToIPNetHookFunc", "(", ")", "DecodeHookFunc", "{", "return", "func", "(", "f", "reflect", ".", "Type", ",", "t", "reflect", ".", "Type", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "f", ".", "Kind", "(", ")", "!=", "reflect", ".", "String", "{", "return", "data", ",", "nil", "\n", "}", "\n", "if", "t", "!=", "reflect", ".", "TypeOf", "(", "net", ".", "IPNet", "{", "}", ")", "{", "return", "data", ",", "nil", "\n", "}", "\n\n", "// Convert it by parsing", "_", ",", "net", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "data", ".", "(", "string", ")", ")", "\n", "return", "net", ",", "err", "\n", "}", "\n", "}" ]
// StringToIPNetHookFunc returns a DecodeHookFunc that converts // strings to net.IPNet
[ "StringToIPNetHookFunc", "returns", "a", "DecodeHookFunc", "that", "converts", "strings", "to", "net", ".", "IPNet" ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L146-L162
train
mitchellh/mapstructure
decode_hooks.go
StringToTimeHookFunc
func StringToTimeHookFunc(layout string) DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(time.Time{}) { return data, nil } // Convert it by parsing return time.Parse(layout, data.(string)) } }
go
func StringToTimeHookFunc(layout string) DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(time.Time{}) { return data, nil } // Convert it by parsing return time.Parse(layout, data.(string)) } }
[ "func", "StringToTimeHookFunc", "(", "layout", "string", ")", "DecodeHookFunc", "{", "return", "func", "(", "f", "reflect", ".", "Type", ",", "t", "reflect", ".", "Type", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "f", ".", "Kind", "(", ")", "!=", "reflect", ".", "String", "{", "return", "data", ",", "nil", "\n", "}", "\n", "if", "t", "!=", "reflect", ".", "TypeOf", "(", "time", ".", "Time", "{", "}", ")", "{", "return", "data", ",", "nil", "\n", "}", "\n\n", "// Convert it by parsing", "return", "time", ".", "Parse", "(", "layout", ",", "data", ".", "(", "string", ")", ")", "\n", "}", "\n", "}" ]
// StringToTimeHookFunc returns a DecodeHookFunc that converts // strings to time.Time.
[ "StringToTimeHookFunc", "returns", "a", "DecodeHookFunc", "that", "converts", "strings", "to", "time", ".", "Time", "." ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L166-L181
train
mitchellh/mapstructure
decode_hooks.go
WeaklyTypedHook
func WeaklyTypedHook( f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) { dataVal := reflect.ValueOf(data) switch t { case reflect.String: switch f { case reflect.Bool: if dataVal.Bool() { return "1", nil } return "0", nil case reflect.Float32: return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil case reflect.Int: return strconv.FormatInt(dataVal.Int(), 10), nil case reflect.Slice: dataType := dataVal.Type() elemKind := dataType.Elem().Kind() if elemKind == reflect.Uint8 { return string(dataVal.Interface().([]uint8)), nil } case reflect.Uint: return strconv.FormatUint(dataVal.Uint(), 10), nil } } return data, nil }
go
func WeaklyTypedHook( f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) { dataVal := reflect.ValueOf(data) switch t { case reflect.String: switch f { case reflect.Bool: if dataVal.Bool() { return "1", nil } return "0", nil case reflect.Float32: return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil case reflect.Int: return strconv.FormatInt(dataVal.Int(), 10), nil case reflect.Slice: dataType := dataVal.Type() elemKind := dataType.Elem().Kind() if elemKind == reflect.Uint8 { return string(dataVal.Interface().([]uint8)), nil } case reflect.Uint: return strconv.FormatUint(dataVal.Uint(), 10), nil } } return data, nil }
[ "func", "WeaklyTypedHook", "(", "f", "reflect", ".", "Kind", ",", "t", "reflect", ".", "Kind", ",", "data", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "dataVal", ":=", "reflect", ".", "ValueOf", "(", "data", ")", "\n", "switch", "t", "{", "case", "reflect", ".", "String", ":", "switch", "f", "{", "case", "reflect", ".", "Bool", ":", "if", "dataVal", ".", "Bool", "(", ")", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "nil", "\n", "case", "reflect", ".", "Float32", ":", "return", "strconv", ".", "FormatFloat", "(", "dataVal", ".", "Float", "(", ")", ",", "'f'", ",", "-", "1", ",", "64", ")", ",", "nil", "\n", "case", "reflect", ".", "Int", ":", "return", "strconv", ".", "FormatInt", "(", "dataVal", ".", "Int", "(", ")", ",", "10", ")", ",", "nil", "\n", "case", "reflect", ".", "Slice", ":", "dataType", ":=", "dataVal", ".", "Type", "(", ")", "\n", "elemKind", ":=", "dataType", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "\n", "if", "elemKind", "==", "reflect", ".", "Uint8", "{", "return", "string", "(", "dataVal", ".", "Interface", "(", ")", ".", "(", "[", "]", "uint8", ")", ")", ",", "nil", "\n", "}", "\n", "case", "reflect", ".", "Uint", ":", "return", "strconv", ".", "FormatUint", "(", "dataVal", ".", "Uint", "(", ")", ",", "10", ")", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "data", ",", "nil", "\n", "}" ]
// WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to // the decoder. // // Note that this is significantly different from the WeaklyTypedInput option // of the DecoderConfig.
[ "WeaklyTypedHook", "is", "a", "DecodeHookFunc", "which", "adds", "support", "for", "weak", "typing", "to", "the", "decoder", ".", "Note", "that", "this", "is", "significantly", "different", "from", "the", "WeaklyTypedInput", "option", "of", "the", "DecoderConfig", "." ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L188-L217
train
mitchellh/mapstructure
mapstructure.go
Decode
func Decode(input interface{}, output interface{}) error { config := &DecoderConfig{ Metadata: nil, Result: output, } decoder, err := NewDecoder(config) if err != nil { return err } return decoder.Decode(input) }
go
func Decode(input interface{}, output interface{}) error { config := &DecoderConfig{ Metadata: nil, Result: output, } decoder, err := NewDecoder(config) if err != nil { return err } return decoder.Decode(input) }
[ "func", "Decode", "(", "input", "interface", "{", "}", ",", "output", "interface", "{", "}", ")", "error", "{", "config", ":=", "&", "DecoderConfig", "{", "Metadata", ":", "nil", ",", "Result", ":", "output", ",", "}", "\n\n", "decoder", ",", "err", ":=", "NewDecoder", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "decoder", ".", "Decode", "(", "input", ")", "\n", "}" ]
// Decode takes an input structure and uses reflection to translate it to // the output structure. output must be a pointer to a map or struct.
[ "Decode", "takes", "an", "input", "structure", "and", "uses", "reflection", "to", "translate", "it", "to", "the", "output", "structure", ".", "output", "must", "be", "a", "pointer", "to", "a", "map", "or", "struct", "." ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/mapstructure.go#L119-L131
train
mitchellh/mapstructure
mapstructure.go
NewDecoder
func NewDecoder(config *DecoderConfig) (*Decoder, error) { val := reflect.ValueOf(config.Result) if val.Kind() != reflect.Ptr { return nil, errors.New("result must be a pointer") } val = val.Elem() if !val.CanAddr() { return nil, errors.New("result must be addressable (a pointer)") } if config.Metadata != nil { if config.Metadata.Keys == nil { config.Metadata.Keys = make([]string, 0) } if config.Metadata.Unused == nil { config.Metadata.Unused = make([]string, 0) } } if config.TagName == "" { config.TagName = "mapstructure" } result := &Decoder{ config: config, } return result, nil }
go
func NewDecoder(config *DecoderConfig) (*Decoder, error) { val := reflect.ValueOf(config.Result) if val.Kind() != reflect.Ptr { return nil, errors.New("result must be a pointer") } val = val.Elem() if !val.CanAddr() { return nil, errors.New("result must be addressable (a pointer)") } if config.Metadata != nil { if config.Metadata.Keys == nil { config.Metadata.Keys = make([]string, 0) } if config.Metadata.Unused == nil { config.Metadata.Unused = make([]string, 0) } } if config.TagName == "" { config.TagName = "mapstructure" } result := &Decoder{ config: config, } return result, nil }
[ "func", "NewDecoder", "(", "config", "*", "DecoderConfig", ")", "(", "*", "Decoder", ",", "error", ")", "{", "val", ":=", "reflect", ".", "ValueOf", "(", "config", ".", "Result", ")", "\n", "if", "val", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "val", "=", "val", ".", "Elem", "(", ")", "\n", "if", "!", "val", ".", "CanAddr", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "config", ".", "Metadata", "!=", "nil", "{", "if", "config", ".", "Metadata", ".", "Keys", "==", "nil", "{", "config", ".", "Metadata", ".", "Keys", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "}", "\n\n", "if", "config", ".", "Metadata", ".", "Unused", "==", "nil", "{", "config", ".", "Metadata", ".", "Unused", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "}", "\n", "}", "\n\n", "if", "config", ".", "TagName", "==", "\"", "\"", "{", "config", ".", "TagName", "=", "\"", "\"", "\n", "}", "\n\n", "result", ":=", "&", "Decoder", "{", "config", ":", "config", ",", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// NewDecoder returns a new decoder for the given configuration. Once // a decoder has been returned, the same configuration must not be used // again.
[ "NewDecoder", "returns", "a", "new", "decoder", "for", "the", "given", "configuration", ".", "Once", "a", "decoder", "has", "been", "returned", "the", "same", "configuration", "must", "not", "be", "used", "again", "." ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/mapstructure.go#L187-L217
train
mitchellh/mapstructure
error.go
WrappedErrors
func (e *Error) WrappedErrors() []error { if e == nil { return nil } result := make([]error, len(e.Errors)) for i, e := range e.Errors { result[i] = errors.New(e) } return result }
go
func (e *Error) WrappedErrors() []error { if e == nil { return nil } result := make([]error, len(e.Errors)) for i, e := range e.Errors { result[i] = errors.New(e) } return result }
[ "func", "(", "e", "*", "Error", ")", "WrappedErrors", "(", ")", "[", "]", "error", "{", "if", "e", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "result", ":=", "make", "(", "[", "]", "error", ",", "len", "(", "e", ".", "Errors", ")", ")", "\n", "for", "i", ",", "e", ":=", "range", "e", ".", "Errors", "{", "result", "[", "i", "]", "=", "errors", ".", "New", "(", "e", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// WrappedErrors implements the errwrap.Wrapper interface to make this // return value more useful with the errwrap and go-multierror libraries.
[ "WrappedErrors", "implements", "the", "errwrap", ".", "Wrapper", "interface", "to", "make", "this", "return", "value", "more", "useful", "with", "the", "errwrap", "and", "go", "-", "multierror", "libraries", "." ]
3536a929edddb9a5b34bd6861dc4a9647cb459fe
https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/error.go#L30-L41
train
perkeep/perkeep
pkg/gpgchallenge/gpg.go
rateLimit
func (cs *Server) rateLimit(keyID, claimedIP string) (isSpammer bool) { cs.whiteListMu.Lock() if _, ok := cs.whiteList[keyID+"-"+claimedIP]; ok { cs.whiteListMu.Unlock() return false } cs.whiteListMu.Unlock() // If they haven't successfully challenged us before, they look suspicious. cs.keyIDSeenMu.Lock() lastSeen, ok := cs.keyIDSeen[keyID] // always keep track of the last time we saw them cs.keyIDSeen[keyID] = time.Now() cs.keyIDSeenMu.Unlock() time.AfterFunc(forgetSeen, func() { // but everyone get a clean slate after a minute of being quiet cs.keyIDSeenMu.Lock() delete(cs.keyIDSeen, keyID) cs.keyIDSeenMu.Unlock() }) if ok { // if we've seen their keyID before, they look even more suspicious, so investigate. if lastSeen.Add(spamDelay).After(time.Now()) { // we kick them out if we saw them less than 5 seconds ago. return true } } cs.IPSeenMu.Lock() lastSeen, ok = cs.IPSeen[claimedIP] // always keep track of the last time we saw them cs.IPSeen[claimedIP] = time.Now() cs.IPSeenMu.Unlock() time.AfterFunc(forgetSeen, func() { // but everyone get a clean slate after a minute of being quiet cs.IPSeenMu.Lock() delete(cs.IPSeen, claimedIP) cs.IPSeenMu.Unlock() }) if ok { // if we've seen their IP before, they look even more suspicious, so investigate. if lastSeen.Add(spamDelay).After(time.Now()) { // we kick them out if we saw them less than 5 seconds ago. return true } } // global rate limit that applies to all strangers at the same time cs.limiter.Wait(context.Background()) return false }
go
func (cs *Server) rateLimit(keyID, claimedIP string) (isSpammer bool) { cs.whiteListMu.Lock() if _, ok := cs.whiteList[keyID+"-"+claimedIP]; ok { cs.whiteListMu.Unlock() return false } cs.whiteListMu.Unlock() // If they haven't successfully challenged us before, they look suspicious. cs.keyIDSeenMu.Lock() lastSeen, ok := cs.keyIDSeen[keyID] // always keep track of the last time we saw them cs.keyIDSeen[keyID] = time.Now() cs.keyIDSeenMu.Unlock() time.AfterFunc(forgetSeen, func() { // but everyone get a clean slate after a minute of being quiet cs.keyIDSeenMu.Lock() delete(cs.keyIDSeen, keyID) cs.keyIDSeenMu.Unlock() }) if ok { // if we've seen their keyID before, they look even more suspicious, so investigate. if lastSeen.Add(spamDelay).After(time.Now()) { // we kick them out if we saw them less than 5 seconds ago. return true } } cs.IPSeenMu.Lock() lastSeen, ok = cs.IPSeen[claimedIP] // always keep track of the last time we saw them cs.IPSeen[claimedIP] = time.Now() cs.IPSeenMu.Unlock() time.AfterFunc(forgetSeen, func() { // but everyone get a clean slate after a minute of being quiet cs.IPSeenMu.Lock() delete(cs.IPSeen, claimedIP) cs.IPSeenMu.Unlock() }) if ok { // if we've seen their IP before, they look even more suspicious, so investigate. if lastSeen.Add(spamDelay).After(time.Now()) { // we kick them out if we saw them less than 5 seconds ago. return true } } // global rate limit that applies to all strangers at the same time cs.limiter.Wait(context.Background()) return false }
[ "func", "(", "cs", "*", "Server", ")", "rateLimit", "(", "keyID", ",", "claimedIP", "string", ")", "(", "isSpammer", "bool", ")", "{", "cs", ".", "whiteListMu", ".", "Lock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "cs", ".", "whiteList", "[", "keyID", "+", "\"", "\"", "+", "claimedIP", "]", ";", "ok", "{", "cs", ".", "whiteListMu", ".", "Unlock", "(", ")", "\n", "return", "false", "\n", "}", "\n", "cs", ".", "whiteListMu", ".", "Unlock", "(", ")", "\n", "// If they haven't successfully challenged us before, they look suspicious.", "cs", ".", "keyIDSeenMu", ".", "Lock", "(", ")", "\n", "lastSeen", ",", "ok", ":=", "cs", ".", "keyIDSeen", "[", "keyID", "]", "\n", "// always keep track of the last time we saw them", "cs", ".", "keyIDSeen", "[", "keyID", "]", "=", "time", ".", "Now", "(", ")", "\n", "cs", ".", "keyIDSeenMu", ".", "Unlock", "(", ")", "\n", "time", ".", "AfterFunc", "(", "forgetSeen", ",", "func", "(", ")", "{", "// but everyone get a clean slate after a minute of being quiet", "cs", ".", "keyIDSeenMu", ".", "Lock", "(", ")", "\n", "delete", "(", "cs", ".", "keyIDSeen", ",", "keyID", ")", "\n", "cs", ".", "keyIDSeenMu", ".", "Unlock", "(", ")", "\n", "}", ")", "\n", "if", "ok", "{", "// if we've seen their keyID before, they look even more suspicious, so investigate.", "if", "lastSeen", ".", "Add", "(", "spamDelay", ")", ".", "After", "(", "time", ".", "Now", "(", ")", ")", "{", "// we kick them out if we saw them less than 5 seconds ago.", "return", "true", "\n", "}", "\n", "}", "\n", "cs", ".", "IPSeenMu", ".", "Lock", "(", ")", "\n", "lastSeen", ",", "ok", "=", "cs", ".", "IPSeen", "[", "claimedIP", "]", "\n", "// always keep track of the last time we saw them", "cs", ".", "IPSeen", "[", "claimedIP", "]", "=", "time", ".", "Now", "(", ")", "\n", "cs", ".", "IPSeenMu", ".", "Unlock", "(", ")", "\n", "time", ".", "AfterFunc", "(", "forgetSeen", ",", "func", "(", ")", "{", "// but everyone get a clean slate after a minute of being quiet", "cs", ".", "IPSeenMu", ".", "Lock", "(", ")", "\n", "delete", "(", "cs", ".", "IPSeen", ",", "claimedIP", ")", "\n", "cs", ".", "IPSeenMu", ".", "Unlock", "(", ")", "\n", "}", ")", "\n", "if", "ok", "{", "// if we've seen their IP before, they look even more suspicious, so investigate.", "if", "lastSeen", ".", "Add", "(", "spamDelay", ")", ".", "After", "(", "time", ".", "Now", "(", ")", ")", "{", "// we kick them out if we saw them less than 5 seconds ago.", "return", "true", "\n", "}", "\n", "}", "\n", "// global rate limit that applies to all strangers at the same time", "cs", ".", "limiter", ".", "Wait", "(", "context", ".", "Background", "(", ")", ")", "\n", "return", "false", "\n", "}" ]
// rateLimit uses the cs.limiter to make sure that any client that hasn't // previously successfully challenged us is rate limited. It also keeps track of // clients that haven't successfully challenged, and it returns true if such a // client should be considered a spammer.
[ "rateLimit", "uses", "the", "cs", ".", "limiter", "to", "make", "sure", "that", "any", "client", "that", "hasn", "t", "previously", "successfully", "challenged", "us", "is", "rate", "limited", ".", "It", "also", "keeps", "track", "of", "clients", "that", "haven", "t", "successfully", "challenged", "and", "it", "returns", "true", "if", "such", "a", "client", "should", "be", "considered", "a", "spammer", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/gpgchallenge/gpg.go#L343-L390
train
perkeep/perkeep
pkg/gpgchallenge/gpg.go
NewClient
func NewClient(keyRing, keyId, challengeIP string) (*Client, error) { signer, err := secretKeyEntity(keyRing, keyId) if err != nil { return nil, fmt.Errorf("could not get signer %v from keyRing %v: %v", keyId, keyRing, err) } cl := &Client{ keyRing: keyRing, keyId: keyId, signer: signer, challengeIP: challengeIP, errc: make(chan error, 1), } handler := &clientHandler{ cl: cl, } cl.handler = handler return cl, nil }
go
func NewClient(keyRing, keyId, challengeIP string) (*Client, error) { signer, err := secretKeyEntity(keyRing, keyId) if err != nil { return nil, fmt.Errorf("could not get signer %v from keyRing %v: %v", keyId, keyRing, err) } cl := &Client{ keyRing: keyRing, keyId: keyId, signer: signer, challengeIP: challengeIP, errc: make(chan error, 1), } handler := &clientHandler{ cl: cl, } cl.handler = handler return cl, nil }
[ "func", "NewClient", "(", "keyRing", ",", "keyId", ",", "challengeIP", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "signer", ",", "err", ":=", "secretKeyEntity", "(", "keyRing", ",", "keyId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyId", ",", "keyRing", ",", "err", ")", "\n", "}", "\n", "cl", ":=", "&", "Client", "{", "keyRing", ":", "keyRing", ",", "keyId", ":", "keyId", ",", "signer", ":", "signer", ",", "challengeIP", ":", "challengeIP", ",", "errc", ":", "make", "(", "chan", "error", ",", "1", ")", ",", "}", "\n", "handler", ":=", "&", "clientHandler", "{", "cl", ":", "cl", ",", "}", "\n", "cl", ".", "handler", "=", "handler", "\n", "return", "cl", ",", "nil", "\n", "}" ]
// NewClient returns a Client. keyRing and keyId are the GPG key ring and key ID // used to fulfill the challenge. challengeIP is the address that client proves // that it owns, by answering the challenge the server sends at this address.
[ "NewClient", "returns", "a", "Client", ".", "keyRing", "and", "keyId", "are", "the", "GPG", "key", "ring", "and", "key", "ID", "used", "to", "fulfill", "the", "challenge", ".", "challengeIP", "is", "the", "address", "that", "client", "proves", "that", "it", "owns", "by", "answering", "the", "challenge", "the", "server", "sends", "at", "this", "address", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/gpgchallenge/gpg.go#L515-L532
train
perkeep/perkeep
pkg/gpgchallenge/gpg.go
Handler
func (cl *Client) Handler() (prefix string, h http.Handler) { return clientHandlerPrefix, cl.handler }
go
func (cl *Client) Handler() (prefix string, h http.Handler) { return clientHandlerPrefix, cl.handler }
[ "func", "(", "cl", "*", "Client", ")", "Handler", "(", ")", "(", "prefix", "string", ",", "h", "http", ".", "Handler", ")", "{", "return", "clientHandlerPrefix", ",", "cl", ".", "handler", "\n", "}" ]
// Handler returns the client's handler, that should be registered with an HTTPS // server for the returned prefix, for the client to be able to receive the // challenge.
[ "Handler", "returns", "the", "client", "s", "handler", "that", "should", "be", "registered", "with", "an", "HTTPS", "server", "for", "the", "returned", "prefix", "for", "the", "client", "to", "be", "able", "to", "receive", "the", "challenge", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/gpgchallenge/gpg.go#L537-L539
train
perkeep/perkeep
pkg/gpgchallenge/gpg.go
listenSelfCheck
func (cl *Client) listenSelfCheck(serverAddr string) error { tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: cl.challengeIP + SNISuffix, }, } httpClient := &http.Client{ Transport: tr, } errc := make(chan error, 1) respc := make(chan *http.Response, 1) var err error var resp *http.Response go func() { resp, err := httpClient.PostForm(fmt.Sprintf("https://localhost:%d%s%s", ClientChallengedPort, clientHandlerPrefix, clientEndPointReady), url.Values{"server": []string{serverAddr}}) errc <- err respc <- resp }() timeout := time.NewTimer(time.Second) defer timeout.Stop() select { case err = <-errc: resp = <-respc case <-timeout.C: return errors.New("The client needs an HTTPS listener for its handler to answer the server's challenge. You need to call Handler and register the http.Handler with an HTTPS server, before calling Challenge.") } if err != nil { return fmt.Errorf("error starting challenge: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusNoContent { return fmt.Errorf("error starting challenge: %v", resp.Status) } return nil }
go
func (cl *Client) listenSelfCheck(serverAddr string) error { tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, ServerName: cl.challengeIP + SNISuffix, }, } httpClient := &http.Client{ Transport: tr, } errc := make(chan error, 1) respc := make(chan *http.Response, 1) var err error var resp *http.Response go func() { resp, err := httpClient.PostForm(fmt.Sprintf("https://localhost:%d%s%s", ClientChallengedPort, clientHandlerPrefix, clientEndPointReady), url.Values{"server": []string{serverAddr}}) errc <- err respc <- resp }() timeout := time.NewTimer(time.Second) defer timeout.Stop() select { case err = <-errc: resp = <-respc case <-timeout.C: return errors.New("The client needs an HTTPS listener for its handler to answer the server's challenge. You need to call Handler and register the http.Handler with an HTTPS server, before calling Challenge.") } if err != nil { return fmt.Errorf("error starting challenge: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusNoContent { return fmt.Errorf("error starting challenge: %v", resp.Status) } return nil }
[ "func", "(", "cl", "*", "Client", ")", "listenSelfCheck", "(", "serverAddr", "string", ")", "error", "{", "tr", ":=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", ",", "ServerName", ":", "cl", ".", "challengeIP", "+", "SNISuffix", ",", "}", ",", "}", "\n", "httpClient", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "tr", ",", "}", "\n", "errc", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "respc", ":=", "make", "(", "chan", "*", "http", ".", "Response", ",", "1", ")", "\n", "var", "err", "error", "\n", "var", "resp", "*", "http", ".", "Response", "\n", "go", "func", "(", ")", "{", "resp", ",", "err", ":=", "httpClient", ".", "PostForm", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ClientChallengedPort", ",", "clientHandlerPrefix", ",", "clientEndPointReady", ")", ",", "url", ".", "Values", "{", "\"", "\"", ":", "[", "]", "string", "{", "serverAddr", "}", "}", ")", "\n", "errc", "<-", "err", "\n", "respc", "<-", "resp", "\n", "}", "(", ")", "\n", "timeout", ":=", "time", ".", "NewTimer", "(", "time", ".", "Second", ")", "\n", "defer", "timeout", ".", "Stop", "(", ")", "\n", "select", "{", "case", "err", "=", "<-", "errc", ":", "resp", "=", "<-", "respc", "\n", "case", "<-", "timeout", ".", "C", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusNoContent", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resp", ".", "Status", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// listenSelfCheck tests whether the client is ready to receive a challenge, // i.e. that the caller has registered the client's handler with a server.
[ "listenSelfCheck", "tests", "whether", "the", "client", "is", "ready", "to", "receive", "a", "challenge", "i", ".", "e", ".", "that", "the", "caller", "has", "registered", "the", "client", "s", "handler", "with", "a", "server", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/gpgchallenge/gpg.go#L576-L612
train
perkeep/perkeep
pkg/blobserver/proxycache/proxycache.go
New
func New(maxBytes int64, cache, origin blobserver.Storage) *Storage { sto := &Storage{ origin: origin, cache: cache, lru: lru.NewUnlocked(0), maxCacheBytes: maxBytes, } return sto }
go
func New(maxBytes int64, cache, origin blobserver.Storage) *Storage { sto := &Storage{ origin: origin, cache: cache, lru: lru.NewUnlocked(0), maxCacheBytes: maxBytes, } return sto }
[ "func", "New", "(", "maxBytes", "int64", ",", "cache", ",", "origin", "blobserver", ".", "Storage", ")", "*", "Storage", "{", "sto", ":=", "&", "Storage", "{", "origin", ":", "origin", ",", "cache", ":", "cache", ",", "lru", ":", "lru", ".", "NewUnlocked", "(", "0", ")", ",", "maxCacheBytes", ":", "maxBytes", ",", "}", "\n", "return", "sto", "\n", "}" ]
// New returns a proxycache blob storage that reads from cache, // then origin, populating cache as needed, up to a total of maxBytes.
[ "New", "returns", "a", "proxycache", "blob", "storage", "that", "reads", "from", "cache", "then", "origin", "populating", "cache", "as", "needed", "up", "to", "a", "total", "of", "maxBytes", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/proxycache/proxycache.go#L77-L85
train
perkeep/perkeep
pkg/blobserver/proxycache/proxycache.go
removeOldest
func (sto *Storage) removeOldest() bool { ctx := context.TODO() k, v := sto.lru.RemoveOldest() if v == nil { return false } sb := v.(blob.SizedRef) // TODO: run these without sto.mu held in background // goroutine? at least pass a context? err := sto.cache.RemoveBlobs(ctx, []blob.Ref{sb.Ref}) if err != nil { log.Printf("proxycache: could not remove oldest blob %v (%d bytes): %v", sb.Ref, sb.Size, err) sto.lru.Add(k, v) return false } if sto.debug { log.Printf("proxycache: removed blob %v (%d bytes)", sb.Ref, sb.Size) } sto.cacheBytes -= int64(sb.Size) return true }
go
func (sto *Storage) removeOldest() bool { ctx := context.TODO() k, v := sto.lru.RemoveOldest() if v == nil { return false } sb := v.(blob.SizedRef) // TODO: run these without sto.mu held in background // goroutine? at least pass a context? err := sto.cache.RemoveBlobs(ctx, []blob.Ref{sb.Ref}) if err != nil { log.Printf("proxycache: could not remove oldest blob %v (%d bytes): %v", sb.Ref, sb.Size, err) sto.lru.Add(k, v) return false } if sto.debug { log.Printf("proxycache: removed blob %v (%d bytes)", sb.Ref, sb.Size) } sto.cacheBytes -= int64(sb.Size) return true }
[ "func", "(", "sto", "*", "Storage", ")", "removeOldest", "(", ")", "bool", "{", "ctx", ":=", "context", ".", "TODO", "(", ")", "\n", "k", ",", "v", ":=", "sto", ".", "lru", ".", "RemoveOldest", "(", ")", "\n", "if", "v", "==", "nil", "{", "return", "false", "\n", "}", "\n", "sb", ":=", "v", ".", "(", "blob", ".", "SizedRef", ")", "\n", "// TODO: run these without sto.mu held in background", "// goroutine? at least pass a context?", "err", ":=", "sto", ".", "cache", ".", "RemoveBlobs", "(", "ctx", ",", "[", "]", "blob", ".", "Ref", "{", "sb", ".", "Ref", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "sb", ".", "Ref", ",", "sb", ".", "Size", ",", "err", ")", "\n", "sto", ".", "lru", ".", "Add", "(", "k", ",", "v", ")", "\n", "return", "false", "\n", "}", "\n", "if", "sto", ".", "debug", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "sb", ".", "Ref", ",", "sb", ".", "Size", ")", "\n", "}", "\n", "sto", ".", "cacheBytes", "-=", "int64", "(", "sb", ".", "Size", ")", "\n", "return", "true", "\n", "}" ]
// must hold sto.mu. // Reports whether an item was removed.
[ "must", "hold", "sto", ".", "mu", ".", "Reports", "whether", "an", "item", "was", "removed", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/proxycache/proxycache.go#L113-L133
train
perkeep/perkeep
server/perkeepd/ui/goui/dirchildren/dirchildren.go
New
func New(authToken, parentDir string, limit int, updadeSearchSession func(string), triggerRender func()) *js.Object { parentDirbr, ok := blob.Parse(parentDir) if !ok { dom.GetWindow().Alert(fmt.Sprintf("invalid parentDir blobRef: %q", parentDir)) return nil } return js.MakeWrapper(&Query{ ParentDir: parentDirbr, AuthToken: authToken, UpdateSearchSession: updadeSearchSession, TriggerRender: triggerRender, Limit: limit, }) }
go
func New(authToken, parentDir string, limit int, updadeSearchSession func(string), triggerRender func()) *js.Object { parentDirbr, ok := blob.Parse(parentDir) if !ok { dom.GetWindow().Alert(fmt.Sprintf("invalid parentDir blobRef: %q", parentDir)) return nil } return js.MakeWrapper(&Query{ ParentDir: parentDirbr, AuthToken: authToken, UpdateSearchSession: updadeSearchSession, TriggerRender: triggerRender, Limit: limit, }) }
[ "func", "New", "(", "authToken", ",", "parentDir", "string", ",", "limit", "int", ",", "updadeSearchSession", "func", "(", "string", ")", ",", "triggerRender", "func", "(", ")", ")", "*", "js", ".", "Object", "{", "parentDirbr", ",", "ok", ":=", "blob", ".", "Parse", "(", "parentDir", ")", "\n", "if", "!", "ok", "{", "dom", ".", "GetWindow", "(", ")", ".", "Alert", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "parentDir", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "js", ".", "MakeWrapper", "(", "&", "Query", "{", "ParentDir", ":", "parentDirbr", ",", "AuthToken", ":", "authToken", ",", "UpdateSearchSession", ":", "updadeSearchSession", ",", "TriggerRender", ":", "triggerRender", ",", "Limit", ":", "limit", ",", "}", ")", "\n", "}" ]
// New returns a new Query as a javascript object, of nil if parentDir is not a // valid blobRef.
[ "New", "returns", "a", "new", "Query", "as", "a", "javascript", "object", "of", "nil", "if", "parentDir", "is", "not", "a", "valid", "blobRef", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/dirchildren/dirchildren.go#L72-L86
train
perkeep/perkeep
server/perkeepd/ui/goui/dirchildren/dirchildren.go
Get
func (q *Query) Get() { if q.isComplete { return } if q.pending { return } q.pending = true go func() { if err := q.get(); err != nil { dom.GetWindow().Alert(fmt.Sprintf("%v", err)) return } q.TriggerRender() }() }
go
func (q *Query) Get() { if q.isComplete { return } if q.pending { return } q.pending = true go func() { if err := q.get(); err != nil { dom.GetWindow().Alert(fmt.Sprintf("%v", err)) return } q.TriggerRender() }() }
[ "func", "(", "q", "*", "Query", ")", "Get", "(", ")", "{", "if", "q", ".", "isComplete", "{", "return", "\n", "}", "\n", "if", "q", ".", "pending", "{", "return", "\n", "}", "\n", "q", ".", "pending", "=", "true", "\n", "go", "func", "(", ")", "{", "if", "err", ":=", "q", ".", "get", "(", ")", ";", "err", "!=", "nil", "{", "dom", ".", "GetWindow", "(", ")", ".", "Alert", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "q", ".", "TriggerRender", "(", ")", "\n", "}", "(", ")", "\n", "}" ]
// Get asynchronously sends the query, if one is not already in flight, or being // processed. It runs q.UpdateSearchSession once the results have been received and // merged with q.Blobs and q.Meta. It runs q.TriggerRender to refresh the DOM with // the new results in the search session.
[ "Get", "asynchronously", "sends", "the", "query", "if", "one", "is", "not", "already", "in", "flight", "or", "being", "processed", ".", "It", "runs", "q", ".", "UpdateSearchSession", "once", "the", "results", "have", "been", "received", "and", "merged", "with", "q", ".", "Blobs", "and", "q", ".", "Meta", ".", "It", "runs", "q", ".", "TriggerRender", "to", "refresh", "the", "DOM", "with", "the", "new", "results", "in", "the", "search", "session", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/dirchildren/dirchildren.go#L114-L129
train
perkeep/perkeep
pkg/sorted/mysql/mysqlkv.go
newKVDB
func newKVDB(cfg jsonconfig.Obj) (sorted.KeyValue, error) { var ( user = cfg.RequiredString("user") database = cfg.RequiredString("database") host = cfg.OptionalString("host", "") password = cfg.OptionalString("password", "") ) if err := cfg.Validate(); err != nil { return nil, err } if !validDatabaseName(database) { return nil, fmt.Errorf("%q looks like an invalid database name", database) } var err error if host != "" { host, err = maybeRemapCloudSQL(host) if err != nil { return nil, err } if !strings.Contains(host, ":") { host += ":3306" } host = "tcp(" + host + ")" } // The DSN does NOT have a database name in it so it's // cacheable and can be shared between different queues & the // index, all sharing the same database server, cutting down // number of TCP connections required. We add the database // name in queries instead. dsn := fmt.Sprintf("%s:%s@%s/", user, password, host) db, err := openOrCachedDB(dsn) if err != nil { return nil, err } if err := CreateDB(db, database); err != nil { return nil, err } return &keyValue{ database: database, dsn: dsn, db: db, KeyValue: &sqlkv.KeyValue{ DB: db, TablePrefix: database + ".", Gate: syncutil.NewGate(20), // arbitrary limit. TODO: configurable, automatically-learned? }, }, nil }
go
func newKVDB(cfg jsonconfig.Obj) (sorted.KeyValue, error) { var ( user = cfg.RequiredString("user") database = cfg.RequiredString("database") host = cfg.OptionalString("host", "") password = cfg.OptionalString("password", "") ) if err := cfg.Validate(); err != nil { return nil, err } if !validDatabaseName(database) { return nil, fmt.Errorf("%q looks like an invalid database name", database) } var err error if host != "" { host, err = maybeRemapCloudSQL(host) if err != nil { return nil, err } if !strings.Contains(host, ":") { host += ":3306" } host = "tcp(" + host + ")" } // The DSN does NOT have a database name in it so it's // cacheable and can be shared between different queues & the // index, all sharing the same database server, cutting down // number of TCP connections required. We add the database // name in queries instead. dsn := fmt.Sprintf("%s:%s@%s/", user, password, host) db, err := openOrCachedDB(dsn) if err != nil { return nil, err } if err := CreateDB(db, database); err != nil { return nil, err } return &keyValue{ database: database, dsn: dsn, db: db, KeyValue: &sqlkv.KeyValue{ DB: db, TablePrefix: database + ".", Gate: syncutil.NewGate(20), // arbitrary limit. TODO: configurable, automatically-learned? }, }, nil }
[ "func", "newKVDB", "(", "cfg", "jsonconfig", ".", "Obj", ")", "(", "sorted", ".", "KeyValue", ",", "error", ")", "{", "var", "(", "user", "=", "cfg", ".", "RequiredString", "(", "\"", "\"", ")", "\n", "database", "=", "cfg", ".", "RequiredString", "(", "\"", "\"", ")", "\n", "host", "=", "cfg", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "password", "=", "cfg", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", ")", "\n", "if", "err", ":=", "cfg", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "validDatabaseName", "(", "database", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "database", ")", "\n", "}", "\n", "var", "err", "error", "\n", "if", "host", "!=", "\"", "\"", "{", "host", ",", "err", "=", "maybeRemapCloudSQL", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "strings", ".", "Contains", "(", "host", ",", "\"", "\"", ")", "{", "host", "+=", "\"", "\"", "\n", "}", "\n", "host", "=", "\"", "\"", "+", "host", "+", "\"", "\"", "\n", "}", "\n", "// The DSN does NOT have a database name in it so it's", "// cacheable and can be shared between different queues & the", "// index, all sharing the same database server, cutting down", "// number of TCP connections required. We add the database", "// name in queries instead.", "dsn", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "user", ",", "password", ",", "host", ")", "\n\n", "db", ",", "err", ":=", "openOrCachedDB", "(", "dsn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "CreateDB", "(", "db", ",", "database", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "keyValue", "{", "database", ":", "database", ",", "dsn", ":", "dsn", ",", "db", ":", "db", ",", "KeyValue", ":", "&", "sqlkv", ".", "KeyValue", "{", "DB", ":", "db", ",", "TablePrefix", ":", "database", "+", "\"", "\"", ",", "Gate", ":", "syncutil", ".", "NewGate", "(", "20", ")", ",", "// arbitrary limit. TODO: configurable, automatically-learned?", "}", ",", "}", ",", "nil", "\n", "}" ]
// newKVDB returns an unusable KeyValue, with a database, but no tables yet. It // should be followed by Wipe or finalize.
[ "newKVDB", "returns", "an", "unusable", "KeyValue", "with", "a", "database", "but", "no", "tables", "yet", ".", "It", "should", "be", "followed", "by", "Wipe", "or", "finalize", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L45-L94
train
perkeep/perkeep
pkg/sorted/mysql/mysqlkv.go
Wipe
func (kv *keyValue) Wipe() error { if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".rows"); err != nil { return err } if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".meta"); err != nil { return err } return kv.finalize() }
go
func (kv *keyValue) Wipe() error { if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".rows"); err != nil { return err } if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".meta"); err != nil { return err } return kv.finalize() }
[ "func", "(", "kv", "*", "keyValue", ")", "Wipe", "(", ")", "error", "{", "if", "_", ",", "err", ":=", "kv", ".", "db", ".", "Exec", "(", "\"", "\"", "+", "kv", ".", "database", "+", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "kv", ".", "db", ".", "Exec", "(", "\"", "\"", "+", "kv", ".", "database", "+", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "kv", ".", "finalize", "(", ")", "\n", "}" ]
// Wipe resets the KeyValue by dropping and recreating the database tables.
[ "Wipe", "resets", "the", "KeyValue", "by", "dropping", "and", "recreating", "the", "database", "tables", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L97-L105
train
perkeep/perkeep
pkg/sorted/mysql/mysqlkv.go
finalize
func (kv *keyValue) finalize() error { if err := createTables(kv.db, kv.database); err != nil { return err } if err := kv.ping(); err != nil { return fmt.Errorf("MySQL db unreachable: %v", err) } version, err := kv.SchemaVersion() if err != nil { return fmt.Errorf("error getting current database schema version: %v", err) } if version == 0 { // Newly created table case if _, err := kv.db.Exec(fmt.Sprintf(`REPLACE INTO %s.meta VALUES ('version', ?)`, kv.database), requiredSchemaVersion); err != nil { return fmt.Errorf("error setting schema version: %v", err) } return nil } if version != requiredSchemaVersion { if version == 20 && requiredSchemaVersion == 21 { fmt.Fprintf(os.Stderr, fixSchema20to21) } if env.IsDev() { // Good signal that we're using the devcam server, so help out // the user with a more useful tip: return sorted.NeedWipeError{ Msg: fmt.Sprintf("database schema version is %d; expect %d (run \"devcam server --wipe\" to wipe both your blobs and re-populate the database schema)", version, requiredSchemaVersion), } } return sorted.NeedWipeError{ Msg: fmt.Sprintf("database schema version is %d; expect %d (need to re-init/upgrade database?)", version, requiredSchemaVersion), } } return nil }
go
func (kv *keyValue) finalize() error { if err := createTables(kv.db, kv.database); err != nil { return err } if err := kv.ping(); err != nil { return fmt.Errorf("MySQL db unreachable: %v", err) } version, err := kv.SchemaVersion() if err != nil { return fmt.Errorf("error getting current database schema version: %v", err) } if version == 0 { // Newly created table case if _, err := kv.db.Exec(fmt.Sprintf(`REPLACE INTO %s.meta VALUES ('version', ?)`, kv.database), requiredSchemaVersion); err != nil { return fmt.Errorf("error setting schema version: %v", err) } return nil } if version != requiredSchemaVersion { if version == 20 && requiredSchemaVersion == 21 { fmt.Fprintf(os.Stderr, fixSchema20to21) } if env.IsDev() { // Good signal that we're using the devcam server, so help out // the user with a more useful tip: return sorted.NeedWipeError{ Msg: fmt.Sprintf("database schema version is %d; expect %d (run \"devcam server --wipe\" to wipe both your blobs and re-populate the database schema)", version, requiredSchemaVersion), } } return sorted.NeedWipeError{ Msg: fmt.Sprintf("database schema version is %d; expect %d (need to re-init/upgrade database?)", version, requiredSchemaVersion), } } return nil }
[ "func", "(", "kv", "*", "keyValue", ")", "finalize", "(", ")", "error", "{", "if", "err", ":=", "createTables", "(", "kv", ".", "db", ",", "kv", ".", "database", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "kv", ".", "ping", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "version", ",", "err", ":=", "kv", ".", "SchemaVersion", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "version", "==", "0", "{", "// Newly created table case", "if", "_", ",", "err", ":=", "kv", ".", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "`REPLACE INTO %s.meta VALUES ('version', ?)`", ",", "kv", ".", "database", ")", ",", "requiredSchemaVersion", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "version", "!=", "requiredSchemaVersion", "{", "if", "version", "==", "20", "&&", "requiredSchemaVersion", "==", "21", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "fixSchema20to21", ")", "\n", "}", "\n", "if", "env", ".", "IsDev", "(", ")", "{", "// Good signal that we're using the devcam server, so help out", "// the user with a more useful tip:", "return", "sorted", ".", "NeedWipeError", "{", "Msg", ":", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "version", ",", "requiredSchemaVersion", ")", ",", "}", "\n", "}", "\n", "return", "sorted", ".", "NeedWipeError", "{", "Msg", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "version", ",", "requiredSchemaVersion", ")", ",", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// finalize should be called on a keyValue initialized with newKVDB.
[ "finalize", "should", "be", "called", "on", "a", "keyValue", "initialized", "with", "newKVDB", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L108-L146
train