github.com/omnigres/cli@v0.1.4/src/github_gist.go (about)

     1  package src
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/PuerkitoBio/goquery"
     6  	"io"
     7  	"net/http"
     8  	"os"
     9  	"path/filepath"
    10  	"regexp"
    11  )
    12  
    13  func IsGitHubGistURL(input string) bool {
    14  	ok, _ := regexp.MatchString("https://gist.github.com/(.+)/(.+)", input)
    15  	return ok
    16  }
    17  
    18  type tempGistDirectory struct {
    19  	path string
    20  }
    21  
    22  func (t *tempGistDirectory) Path() string {
    23  	return t.path
    24  }
    25  
    26  func (t *tempGistDirectory) Close() error {
    27  	return os.RemoveAll(t.path)
    28  }
    29  
    30  func getGitHubGist(input string) (srcdir SourceDirectory, err error) {
    31  	var response *http.Response
    32  	response, err = http.Get(input)
    33  	if err != nil {
    34  		return
    35  	}
    36  	defer response.Body.Close()
    37  	if response.StatusCode != 200 {
    38  		err = fmt.Errorf("status code error: %d %s", response.StatusCode, response.Status)
    39  		return
    40  	}
    41  	var doc *goquery.Document
    42  	doc, err = goquery.NewDocumentFromReader(response.Body)
    43  	if err != nil {
    44  		return
    45  	}
    46  	var dir string
    47  	dir, err = os.MkdirTemp("", "omnigres-gist")
    48  	if err != nil {
    49  		return
    50  	}
    51  
    52  	doc.Find("a").Each(func(i int, s *goquery.Selection) {
    53  		href, _ := s.Attr("href")
    54  		if ok, _ := regexp.MatchString("/raw/", href); ok {
    55  			response, err = http.Get("https://gist.github.com" + href)
    56  			if err != nil {
    57  				return
    58  			}
    59  			defer response.Body.Close()
    60  			if response.StatusCode != 200 {
    61  				err = fmt.Errorf("status code error: %d %s", response.StatusCode, response.Status)
    62  				return
    63  			}
    64  			filename := filepath.Base(href)
    65  			var file *os.File
    66  
    67  			file, err = os.Create(filepath.Join(dir, filename))
    68  			if err != nil {
    69  				return
    70  			}
    71  			defer file.Close()
    72  			_, err = io.Copy(file, response.Body)
    73  
    74  			if err != nil {
    75  				return
    76  			}
    77  		}
    78  	})
    79  	srcdir = &tempGistDirectory{path: dir}
    80  	return
    81  }