You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tool.go 11KB

9 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
10 years ago
10 years ago
8 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
7 years ago
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package base
  5. import (
  6. "crypto/md5"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "crypto/sha256"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "fmt"
  13. "io"
  14. "math"
  15. "net/http"
  16. "net/url"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "runtime"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "unicode"
  25. "code.gitea.io/gitea/modules/git"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/setting"
  28. "github.com/Unknwon/com"
  29. )
  30. // EncodeMD5 encodes string to md5 hex value.
  31. func EncodeMD5(str string) string {
  32. m := md5.New()
  33. _, _ = m.Write([]byte(str))
  34. return hex.EncodeToString(m.Sum(nil))
  35. }
  36. // EncodeSha1 string to sha1 hex value.
  37. func EncodeSha1(str string) string {
  38. h := sha1.New()
  39. _, _ = h.Write([]byte(str))
  40. return hex.EncodeToString(h.Sum(nil))
  41. }
  42. // EncodeSha256 string to sha1 hex value.
  43. func EncodeSha256(str string) string {
  44. h := sha256.New()
  45. _, _ = h.Write([]byte(str))
  46. return hex.EncodeToString(h.Sum(nil))
  47. }
  48. // ShortSha is basically just truncating.
  49. // It is DEPRECATED and will be removed in the future.
  50. func ShortSha(sha1 string) string {
  51. return TruncateString(sha1, 10)
  52. }
  53. // BasicAuthDecode decode basic auth string
  54. func BasicAuthDecode(encoded string) (string, string, error) {
  55. s, err := base64.StdEncoding.DecodeString(encoded)
  56. if err != nil {
  57. return "", "", err
  58. }
  59. auth := strings.SplitN(string(s), ":", 2)
  60. return auth[0], auth[1], nil
  61. }
  62. // BasicAuthEncode encode basic auth string
  63. func BasicAuthEncode(username, password string) string {
  64. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  65. }
  66. // GetRandomBytesAsBase64 generates a random base64 string from n bytes
  67. func GetRandomBytesAsBase64(n int) string {
  68. bytes := make([]byte, 32)
  69. _, err := io.ReadFull(rand.Reader, bytes)
  70. if err != nil {
  71. log.Fatal("Error reading random bytes: %v", err)
  72. }
  73. return base64.RawURLEncoding.EncodeToString(bytes)
  74. }
  75. // VerifyTimeLimitCode verify time limit code
  76. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  77. if len(code) <= 18 {
  78. return false
  79. }
  80. // split code
  81. start := code[:12]
  82. lives := code[12:18]
  83. if d, err := com.StrTo(lives).Int(); err == nil {
  84. minutes = d
  85. }
  86. // right active code
  87. retCode := CreateTimeLimitCode(data, minutes, start)
  88. if retCode == code && minutes > 0 {
  89. // check time is expired or not
  90. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  91. now := time.Now()
  92. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  93. return true
  94. }
  95. }
  96. return false
  97. }
  98. // TimeLimitCodeLength default value for time limit code
  99. const TimeLimitCodeLength = 12 + 6 + 40
  100. // CreateTimeLimitCode create a time limit code
  101. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  102. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  103. format := "200601021504"
  104. var start, end time.Time
  105. var startStr, endStr string
  106. if startInf == nil {
  107. // Use now time create code
  108. start = time.Now()
  109. startStr = start.Format(format)
  110. } else {
  111. // use start string create code
  112. startStr = startInf.(string)
  113. start, _ = time.ParseInLocation(format, startStr, time.Local)
  114. startStr = start.Format(format)
  115. }
  116. end = start.Add(time.Minute * time.Duration(minutes))
  117. endStr = end.Format(format)
  118. // create sha1 encode string
  119. sh := sha1.New()
  120. _, _ = sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  121. encoded := hex.EncodeToString(sh.Sum(nil))
  122. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  123. return code
  124. }
  125. // HashEmail hashes email address to MD5 string.
  126. // https://en.gravatar.com/site/implement/hash/
  127. func HashEmail(email string) string {
  128. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  129. }
  130. // DefaultAvatarLink the default avatar link
  131. func DefaultAvatarLink() string {
  132. return setting.AppSubURL + "/img/avatar_default.png"
  133. }
  134. // DefaultAvatarSize is a sentinel value for the default avatar size, as
  135. // determined by the avatar-hosting service.
  136. const DefaultAvatarSize = -1
  137. // libravatarURL returns the URL for the given email. This function should only
  138. // be called if a federated avatar service is enabled.
  139. func libravatarURL(email string) (*url.URL, error) {
  140. urlStr, err := setting.LibravatarService.FromEmail(email)
  141. if err != nil {
  142. log.Error("LibravatarService.FromEmail(email=%s): error %v", email, err)
  143. return nil, err
  144. }
  145. u, err := url.Parse(urlStr)
  146. if err != nil {
  147. log.Error("Failed to parse libravatar url(%s): error %v", urlStr, err)
  148. return nil, err
  149. }
  150. return u, nil
  151. }
  152. // SizedAvatarLink returns a sized link to the avatar for the given email
  153. // address.
  154. func SizedAvatarLink(email string, size int) string {
  155. var avatarURL *url.URL
  156. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  157. var err error
  158. avatarURL, err = libravatarURL(email)
  159. if err != nil {
  160. return DefaultAvatarLink()
  161. }
  162. } else if !setting.DisableGravatar {
  163. // copy GravatarSourceURL, because we will modify its Path.
  164. copyOfGravatarSourceURL := *setting.GravatarSourceURL
  165. avatarURL = &copyOfGravatarSourceURL
  166. avatarURL.Path = path.Join(avatarURL.Path, HashEmail(email))
  167. } else {
  168. return DefaultAvatarLink()
  169. }
  170. vals := avatarURL.Query()
  171. vals.Set("d", "identicon")
  172. if size != DefaultAvatarSize {
  173. vals.Set("s", strconv.Itoa(size))
  174. }
  175. avatarURL.RawQuery = vals.Encode()
  176. return avatarURL.String()
  177. }
  178. // AvatarLink returns relative avatar link to the site domain by given email,
  179. // which includes app sub-url as prefix. However, it is possible
  180. // to return full URL if user enables Gravatar-like service.
  181. func AvatarLink(email string) string {
  182. return SizedAvatarLink(email, DefaultAvatarSize)
  183. }
  184. // Storage space size types
  185. const (
  186. Byte = 1
  187. KByte = Byte * 1024
  188. MByte = KByte * 1024
  189. GByte = MByte * 1024
  190. TByte = GByte * 1024
  191. PByte = TByte * 1024
  192. EByte = PByte * 1024
  193. )
  194. func logn(n, b float64) float64 {
  195. return math.Log(n) / math.Log(b)
  196. }
  197. func humanateBytes(s uint64, base float64, sizes []string) string {
  198. if s < 10 {
  199. return fmt.Sprintf("%dB", s)
  200. }
  201. e := math.Floor(logn(float64(s), base))
  202. suffix := sizes[int(e)]
  203. val := float64(s) / math.Pow(base, math.Floor(e))
  204. f := "%.0f"
  205. if val < 10 {
  206. f = "%.1f"
  207. }
  208. return fmt.Sprintf(f+"%s", val, suffix)
  209. }
  210. // FileSize calculates the file size and generate user-friendly string.
  211. func FileSize(s int64) string {
  212. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  213. return humanateBytes(uint64(s), 1024, sizes)
  214. }
  215. // Subtract deals with subtraction of all types of number.
  216. func Subtract(left interface{}, right interface{}) interface{} {
  217. var rleft, rright int64
  218. var fleft, fright float64
  219. var isInt = true
  220. switch v := left.(type) {
  221. case int:
  222. rleft = int64(v)
  223. case int8:
  224. rleft = int64(v)
  225. case int16:
  226. rleft = int64(v)
  227. case int32:
  228. rleft = int64(v)
  229. case int64:
  230. rleft = v
  231. case float32:
  232. fleft = float64(v)
  233. isInt = false
  234. case float64:
  235. fleft = v
  236. isInt = false
  237. }
  238. switch v := right.(type) {
  239. case int:
  240. rright = int64(v)
  241. case int8:
  242. rright = int64(v)
  243. case int16:
  244. rright = int64(v)
  245. case int32:
  246. rright = int64(v)
  247. case int64:
  248. rright = v
  249. case float32:
  250. fright = float64(v)
  251. isInt = false
  252. case float64:
  253. fright = v
  254. isInt = false
  255. }
  256. if isInt {
  257. return rleft - rright
  258. }
  259. return fleft + float64(rleft) - (fright + float64(rright))
  260. }
  261. // EllipsisString returns a truncated short string,
  262. // it appends '...' in the end of the length of string is too large.
  263. func EllipsisString(str string, length int) string {
  264. if length <= 3 {
  265. return "..."
  266. }
  267. if len(str) <= length {
  268. return str
  269. }
  270. return str[:length-3] + "..."
  271. }
  272. // TruncateString returns a truncated string with given limit,
  273. // it returns input string if length is not reached limit.
  274. func TruncateString(str string, limit int) string {
  275. if len(str) < limit {
  276. return str
  277. }
  278. return str[:limit]
  279. }
  280. // StringsToInt64s converts a slice of string to a slice of int64.
  281. func StringsToInt64s(strs []string) ([]int64, error) {
  282. ints := make([]int64, len(strs))
  283. for i := range strs {
  284. n, err := com.StrTo(strs[i]).Int64()
  285. if err != nil {
  286. return ints, err
  287. }
  288. ints[i] = n
  289. }
  290. return ints, nil
  291. }
  292. // Int64sToStrings converts a slice of int64 to a slice of string.
  293. func Int64sToStrings(ints []int64) []string {
  294. strs := make([]string, len(ints))
  295. for i := range ints {
  296. strs[i] = strconv.FormatInt(ints[i], 10)
  297. }
  298. return strs
  299. }
  300. // Int64sToMap converts a slice of int64 to a int64 map.
  301. func Int64sToMap(ints []int64) map[int64]bool {
  302. m := make(map[int64]bool)
  303. for _, i := range ints {
  304. m[i] = true
  305. }
  306. return m
  307. }
  308. // Int64sContains returns if a int64 in a slice of int64
  309. func Int64sContains(intsSlice []int64, a int64) bool {
  310. for _, c := range intsSlice {
  311. if c == a {
  312. return true
  313. }
  314. }
  315. return false
  316. }
  317. // IsLetter reports whether the rune is a letter (category L).
  318. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  319. func IsLetter(ch rune) bool {
  320. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  321. }
  322. // IsTextFile returns true if file content format is plain text or empty.
  323. func IsTextFile(data []byte) bool {
  324. if len(data) == 0 {
  325. return true
  326. }
  327. return strings.Contains(http.DetectContentType(data), "text/")
  328. }
  329. // IsImageFile detects if data is an image format
  330. func IsImageFile(data []byte) bool {
  331. return strings.Contains(http.DetectContentType(data), "image/")
  332. }
  333. // IsPDFFile detects if data is a pdf format
  334. func IsPDFFile(data []byte) bool {
  335. return strings.Contains(http.DetectContentType(data), "application/pdf")
  336. }
  337. // IsVideoFile detects if data is an video format
  338. func IsVideoFile(data []byte) bool {
  339. return strings.Contains(http.DetectContentType(data), "video/")
  340. }
  341. // IsAudioFile detects if data is an video format
  342. func IsAudioFile(data []byte) bool {
  343. return strings.Contains(http.DetectContentType(data), "audio/")
  344. }
  345. // EntryIcon returns the octicon class for displaying files/directories
  346. func EntryIcon(entry *git.TreeEntry) string {
  347. switch {
  348. case entry.IsLink():
  349. te, err := entry.FollowLink()
  350. if err != nil {
  351. log.Debug(err.Error())
  352. return "file-symlink-file"
  353. }
  354. if te.IsDir() {
  355. return "file-symlink-directory"
  356. }
  357. return "file-symlink-file"
  358. case entry.IsDir():
  359. return "file-directory"
  360. case entry.IsSubModule():
  361. return "file-submodule"
  362. }
  363. return "file-text"
  364. }
  365. // SetupGiteaRoot Sets GITEA_ROOT if it is not already set and returns the value
  366. func SetupGiteaRoot() string {
  367. giteaRoot := os.Getenv("GITEA_ROOT")
  368. if giteaRoot == "" {
  369. _, filename, _, _ := runtime.Caller(0)
  370. giteaRoot = strings.TrimSuffix(filename, "modules/base/tool.go")
  371. wd, err := os.Getwd()
  372. if err != nil {
  373. rel, err := filepath.Rel(giteaRoot, wd)
  374. if err != nil && strings.HasPrefix(filepath.ToSlash(rel), "../") {
  375. giteaRoot = wd
  376. }
  377. }
  378. if _, err := os.Stat(filepath.Join(giteaRoot, "gitea")); os.IsNotExist(err) {
  379. giteaRoot = ""
  380. } else if err := os.Setenv("GITEA_ROOT", giteaRoot); err != nil {
  381. giteaRoot = ""
  382. }
  383. }
  384. return giteaRoot
  385. }